38

You can use the getTime method to get the milliseconds between them and then convert to whatever unit you need: Long dt1Long = DateTime.now().addDays(-1).getTime(); Long dt2Long = DateTime.now().getTime(); Long milliseconds = dt2Long - dt1Long; Long seconds = milliseconds / 1000; Long minutes = seconds / 60; Long hours = minutes / 60; Long days = hours / 24;...


30

Rich's answer was promising, so I tried to figure out why it wouldn't work, so did a bit of debugging and found that something like this: System.debug(JSON.deserialize(JSON.serialize(Datetime.now()), Datetime.class)); would print the current Datetime, and that System.debug(JSON.serialize(Datetime.now()); does in fact serialize to ISo 8601 format, so ...


22

Datetime objects have this date method: date() Returns the Date component of a Datetime in the local time zone of the context user. so your code can use it like this: Datetime dt = (Datetime) resultSet.get('LastModifiedDate'); sf.lastModifiedDate = dt.date(); (Generally you would need a null check in the code but as LastModifiedDate always has a ...


22

You can do this using Apex' Date class: acc.effectiveDate__c = Date.newInstance(2016, 12, 9); For more information check out the documentation: Apex Developer Guide - Date Class


21

Use daysBetween date startDate = date.newInstance(2008, 1, 1); date dueDate = date.newInstance(2008, 1, 30); integer numberDaysDue = startDate.daysBetween(dueDate); Here ist the doc: Date Methods


20

UPDATE For the following format February 2, 2013 please use: Datetime myDatetime = Datetime.now(); String myDatetimeStr = myDatetime.format('MMMM d, yyyy'); Im using the following functions for the timestamp: // This method returns a whole timestamp as a string public String timeStamp(){ Datetime dt = Datetime.NOW(); String day = checkLength(...


20

They give you the same data. Their descriptions are almost verbatim as well: System.now() Returns the current date and time in the GMT time zone. Datetime.now() Returns the current Datetime based on a GMT calendar. And for today they are indeed verbatim: System.today() Returns the current date in the current user's time zone. Date.today() Returns the ...


19

DateTime dt = DateTime.now(); String formattedDt = dt.format('yyyy-MM-dd\'T\'hh:mm:ss\'Z\''); Update: Another option is to use SOQL dynamic binding, no formatting required. DateTime dt = DateTime.now(); String query = 'SELECT Id FROM User WHERE SystemModstamp > :dt ' List<SObject> results = Database.query(query);


18

You are looking for the Datetime.format() method. In your instance, you should be able to use: String formattedDate = relatedTo.my_date__c.format('MMMM d, yyyy'); This method utilizes the same format as the Java SimpleDateFormat. Specifically, you should read up on the Date & Time Patterns section and review the table there. It will allow you to format ...


18

Three problems here: (a) Date receiving DateTime value. The value should be "YYYY-MM-DD" only. (b) Decimal receiving String value. The value should not be in quotes. (c) You must not have a trailing comma. JSON-compliant strings are more strict than normal JavaScript. [{ "name":"OpportunityABC", "CloseDate":"2017-06-03", "StageName":"Pre-...


17

I can replicate it, and by removing the * 1000 and appending 3 zeros, I got "Invalid Integer". So what I believe is that 1391529600 * 1000 is being evaluated as an integer type and so overflowing. You can create the Long value using the L notation like so: system.debug(DateTime.newInstance(1391529600000L)); To get the epoch from a datetime ...


17

Actually... the datetime format is right. The capital Y merge field is the WEEK YEAR - which from the 27th December 2015 is IN 2016! The lower case y merge field is the CALENDAR YEAR - which will be 2015 as expected. Change your line to System.debug('~~~~~localDateTime'+localDateTime.format('MM/dd/yyyy')); and you will see your logs play properly. ...


15

This is known as a "Unix Timestamp" (number of milliseconds since January 1st, 1970, 00:00:00 GMT). In Apex Code, you can use DateTime.newInstance(unixTimestamp) to return a DateTime that contains the formatted date/time value. In JavaScript, use new Date(unitTimestamp) to get the same result. To convert back, in Apex Code, use myDate.getTime(), and in ...


15

The timestamp that salesforce returns are the number of millisecons from January 1 1970, not the number of seconds.


15

The problem was with initializing the DateTime variable by casting from a Date. As the Date had no Timezone information, the resulting DateTime was created at UTC+0. For Pacific Standard Time at the point of testing this put the current DateTime on the previous day. Instead of directly casting the Date to a DateTime, the DateTime.newInstance(date, time) ...


14

Well I came across this problem and this gets uglier when you are converting the double value returned from apex into date, the timezone offset gets added into the time and can even change the date!!!. Well to fix this I wrote a simple js function which nulifies the effect by subtracting the offset back from the date. function normalizeDate(mydate){ ...


14

Historically, only the System methods were originally available (System.now and System.today). The newer methods were added later, presumably because people felt it was logical that you'd find the current date in a class called Date, and the current time in a class called DateTime. They are exactly identical in behavior, so feel free to use whichever you ...


13

The Timezone class is new in Spring 13 and includes the getOffset() method to get "the time zone offset, in milliseconds, of the specified date to the GMT time zone." It should be possible to use this information to do the timezone conversion. You would need a list of time zone ids. According to the docs these values match those in the Java TimeZone ...


13

Using the example given in the DateTime class and calling the formatGMT(string) method with a formatting string found in the Java SimpleDateFormat examples: DateTime myDateTime = DateTime.newInstance(1993, 6, 6, 3, 3, 3); String formatted = myDateTime.formatGMT('yyyy-MM-dd\'T\'HH:mm:ss.SSSZ'); system.debug(formatted); Produces this result: 15:41:47:003 ...


12

Your question is not very clear to me, but my two possible interpretations are you want to format the current Datetime according to your locale, or you want to adjust the System.now() result to account for the local time zone. If you just want a locale-specific formatted string to represent the current Datetime, use: String formatted = Datetime.now()....


12

Use DateTime's formatGMT to format the time according to your specs in GMT. String formatedDt = dt.formatGMT('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');


11

Not a bug. This is documented, make sure your source file has the dates with this format. (Specify the time) YYYY-MM-DDThh:mm:ssZ http://help.salesforce.com/HTViewSolution?id=000005099&language=en_US


11

Very interesting question. I did some research on it and found this gitHub repository, someone has tried to play with default values of all kinds of basic types. Scene 1: Simply putting the below line doesn't work. <aura:attribute type="Datetime" name="datetimeDefaultWithTimeString" default="2013-03-06T10:17:36.789Z"/> however if you do the exact ...


10

Map <String, Integer> monthNames = new Map <String, Integer> {'Jan'=>1, 'Feb'=>2, 'Mar'=>3, 'Apr'=>4, 'May'=>5, 'Jun'=>6, 'Jul'=>7, 'Aug'=>8, 'Sep'=>9, 'Oct'=>10, 'Nov'=>11, 'Dec'=>12}; List <String> stringParts = 'Wed Aug 07 04:30:00 GMT 2013'.split(' '); List <String> timeParts = stringParts[3]....


10

Use DateTime parse method: e.g.; Datetime dt = DateTime.parse('10/14/2011 11:46 AM'); will return date instance of String. or try String stringDate = '2013-10-05 20:03:20'; Datetime myDate = datetime.valueOf(stringDate);


10

I know this question is very old, but it comes up as one of the top results on google for Salesforce date timezone questions. DateTime fields store the time information in UTC and display the appropriate date and time to the user based on the user's personal timezone settings. Date fields contain no time information and completely ignore timezones. ...


10

LaceySnr has a solid answer to #1, but #2 is still unanswered, so I'll note that the DateTime.getTime() method returns the number of milliseconds since Jan 1, 1970, so you'll need to divide by 1000 to get standard unix time, which is the number of seconds since the epoch. If you want to work with this number you'll need to ensure you store it in a Long, and ...


10

I think the time wasn't in the correct format DateTime testDate = DateTime.now(); System.assertEquals('"' + testDate.formatGMT('yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\'' + '"'), JSON.serialize(testDate));


10

Attribution Use: system.debug(Datetime.now().formatGMT('yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\'')); The esteemed Mr Ballinger also recommends the following, but it is wrapped in double quotes and slower, so I would probably not use it, myself. system.debug(JSON.serialize(Datetime.now()));


10

To parse DateTimes in this ISO format, you need to use JSON deserialization. String data = '2019-01-03T00:26:01.711-02:00'; Datetime dt = (DateTime)JSON.deserialize('"' + data + '"', DateTime.class); The JSON parser understands ISO format, while DateTime.parse() uses the running user's locale settings.


Only top voted, non community-wiki answers of a minimum length are eligible