Unix seconds to date time?

  

What's the best method to convert unix timestamp to DateTime?

I've been trying this method, but no success.

AddSeconds(NewDateTime(1970,1,1,0,0,0), DecimalToInteger(UnixTimestamp))


Hi Daniel,


What are you getting?

The wrong value or not working at all?

It should kind of work, but you probably still missing the timezone and daylight savings since the platform date times are all LocalTimes and not UTC.


Look at this piece of code that I copied from the platform REST API's code (that does this type of conversion automatically). You can easily place it in an extension:

C#:

           long t = long.Parse(source);

           return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(t).ToLocalTime();


Java:
            try {
                long secondsSinceEpoch = Long.parseLong(source);
                Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
                cal.setTime(new Date(secondsSinceEpoch * 1000));
                return cal.getTime();
            } catch (NumberFormatException e){
                throw new IllegalArgumentException("The value '" + source + "' is not valid for Unix DateTime.");
            }


Regards,
João Rosado


Regards,
João Rosado

Solution

Try it like this: AddSeconds(NewDateTime(1970,1,1,0,0,0),UnixTimestamp)

Solution

I needed this functionality and tried the solution in previous post (by Carlos Conde and marked as Solution). It did NOT work.

The reasons were

  • AddSeconds expects 'Seconds' to be added to the given DateTime object.
  • AddSeconds expects 'Integer' value where as Unix timestamp is a Long Integer and is milliseconds.

So I tweaked the solution like the following assuming that UnixTimestamp is a text variable:

AddSeconds(NewDateTime(1970, 1, 1, 0, 0, 0), TextToLongInteger(UnixTimestamp) / 1000)

Here is the Java Code to verify what I have pointed out:

long timestamp = 1427997766000L;

System.out.println("Date for " + timestamp + " is " + new java.util.Date(timestamp));

System.out.println("Integer value for " + timestamp + " is " + (int)timestamp);

System.out.println("Date for " + timestamp + ", considered as integer value, is " + new java.util.Date((int)timestamp));

Hello Ali,

This thread contains discussion you may find useful.

There is also a component that does the conversion, created by our community. The name of the component is Epoch, and maybe you can modify it to fit your needs.