0
String dtString = '"'+ String.valueOf(Date.today()) + 'T00:00:00.000Z"';
DateTime dt = (DateTime)JSON.deserialize(dtString, DateTime.class);
System.debug(dt); //This prints 2016-08-30 00:00:00
System.debug(dt.date()); //This prints 2016-08-29 00:00:00
System.assert(dt.date() == System.now().date());

Not sure what is wrong with the above code, it keeps failing. As you can see on line 3 and 4 the debug statement prints different values.

I referred to this question on how to properly de-serialize a datetime.

  • Just curious if you are tied to the format in dtString, if this is all hypothetical, etc? – Adrian Larson Aug 30 '16 at 21:35
  • This is not hypothetical :) I have a valid use case. – javanoob Aug 30 '16 at 21:37
  • But really, can you change the format? Using Datetime.valueOf would be more reliable. – Adrian Larson Aug 30 '16 at 22:04
  • @AdrianLarson, Not sure if I understand your comment correctly but the return type for Datetime.valueOf is DateTime but I need in string format which can be desrialized into Datetime. – javanoob Aug 30 '16 at 22:16
  • But why does it have to be deserialization? – Adrian Larson Aug 30 '16 at 22:19
3

DateTime.Date() returns the local time zone's date, which you're then converting into GMT by adding T00:00:00.000Z; in effect, dt is now rounded to the nearest date in GMT format. For example, if you run this at 8pm MST, you're four hours off, but if you run this at 1pm MST, then you're 13 hours off in the other direction. You'll notice that dt.date() is again returning the date in your local time zone; midnight GMT is still the previous day for the Western half of the world. However, DateTime.now() is always expressed in GMT, which means that it's again "tomorrow" from the code's point of view. Coincidentally, if you ran this code in the morning, your assertion would pass. Alternatively, if you used DateTime.dateGMT(), you'd get the correct date in your string, and there wouldn't be a time zone skew.

  • This solved the problem for me. I used something like this to construct the time part DateTime nowDT = System.now(); String timeString = String.valueOf(nowDT.hour()) + ':' + String.valueOf(nowDT.minute()) + ':' + String.valueOf(nowDT.second()); – javanoob Aug 30 '16 at 22:11
0

I suggest use System methods because they work faster! The difference is quit small, until you are calling these methods millions of times: For Date.today(), the cost per invocation is about 4.43µs, whereas System.today() costs about 3.85µs per invocation, a difference of about ~15%. For Datetime.now(), the cost per invocation is about 3.48µs, whereas System.now() costs about 2.97µs per invocation, a difference of ~17%.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.