Datetime from Unix time miliseconds
3 views (last 30 days)
Show older comments
Hello,
I am using a data source that gives a unix time(down to miliseconds), I want to convert this to a date string, I am currently using
dt = datestr(datetime(values(1)/1000, 'ConvertFrom', 'posixtime') + hours(2)); %add 2 hours for gmt +2
The division by 1000 is because the datestring can't handle mili second unix time.
With google I can't find a way to tell matlab to include milliseconds to datetime, but I really need the milliseconds. Did I overlook something?
Thanks in advance,
Bearpie
P.S. Matlab 2016A
Accepted Answer
More Answers (2)
Peter Perkins
on 3 Aug 2016
It's not entirely clear to me what you're starting out with. "unix time" isiusually measure in seconds since 1970, you may have seconds with a fraction, or you may have seconds*1000 as an integer. I'm thinking the latter based on your code. You're also correcting for local time zone in your string.
>> unixmillis = 1470243132021
unixmillis =
1470243132021
>> t = datetime(unixmillis/1000,'ConvertFrom','posixTime','TimeZone','America/New_York','Format','dd-MMM-yyyy HH:mm:ss.SSS')
t =
03-Aug-2016 12:52:12.021
>> char(t)
ans =
03-Aug-2016 12:52:12.021
Numerically, the division by 1000 isn't the greatest, but for many purposes (including, making a string), it's good enough. You could also do this:
>> datetime(1970,1,1,'Format','dd-MMM-yyyy HH:mm:ss.SSS') + milliseconds(unixmillis)
ans =
03-Aug-2016 16:52:12.021
0 Comments
Guillaume
on 17 Jun 2016
Both datetime and datestr support milliseconds just fine. You just need to tell them you want the milliseconds displayed.
To force datestr to show milliseconds:
dt = datestr(yourdatetime, 'dd-mmm-yyyy HH:MM:SS:FFF'); %FFF is for millisecond
Once you've converted to datestring you've lost all the information not encoded in the string, so instead I would keep the information as datetime, and convert the datetime to a string as required
yourdatetime.Format = 'dd-MMM-yyyy HH:mm:ss SSS'); %note that datetime format syntax is not the same as datestr
c = char(yourdatetime) %to get a string out of a datetime
0 Comments
See Also
Categories
Find more on Dates and Time in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!