Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

I found the question about converting epoch time to normal time, but I'm having two problems:

  1. When I run DateTime.newInstance(1391529600 * 1000) I am getting the wrong answer
  2. I want to convert normal time to epoch time

1: I have been typing the following into Execute Anonymous:

system.debug(DateTime.newInstance(1391529600 * 1000));

By my calculations (and some websites I found) that should give me 4 Feb, 2014, 16:00:00 GMT.

Apex gives me

1969-12-31 12:56:36

Clearly, this is incorrect (and it's even before 1/1/1970). Can anyone replicate my situation?

2: I also want to change the current datetime (GMT) to epoch time, returning the number of seconds or milliseconds since 1/1/1970. I could break things into parts, but that seems an awful lot of script statements to do something that should be fairly easy, I'd hope.

Thanks for the help!

share|improve this question
add comment

2 Answers 2

up vote 8 down vote accepted

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 variable you can just call the getTime() instance method:

Datetime dt = Datetime.now();
Long l = dt.getTime();
system.debug(l);
system.debug(DateTime.newInstance(l));

produces:

USER_DEBUG|[7]|DEBUG|1391560453900

USER_DEBUG|[9]|DEBUG|2014-02-05 00:34:13

share|improve this answer
add comment

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 not an Integer type.

share|improve this answer
2  
You must have been writing that while I was working on my edit ;) –  LaceySnr Feb 5 at 0:38
    
Very nice. I'll be careful to use a Long and not an Integer as I move back and forth between the two. Thanks. –  DavidSchach Feb 6 at 5:01
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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