Datetime from Unix time miliseconds

3 ビュー (過去 30 日間)
Bearpie
Bearpie 2016 年 6 月 17 日
回答済み: Peter Perkins 2016 年 8 月 3 日
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
  1 件のコメント
Bearpie
Bearpie 2016 年 6 月 20 日
I ended up removing the last 3 chars from the unix time in ms to get it in seconds. Than I parsed the last 3 to an int and added that to datetime by using
datetime + milliseconds(lastThreeChars);
This added the milliseconds to my datetime!

サインインしてコメントする。

採用された回答

Bearpie
Bearpie 2016 年 6 月 20 日
I ended up removing the last 3 chars from the unix time in ms to get it in seconds. Than I parsed the last 3 to an int and added that to datetime by using
datetime + milliseconds(lastThreeChars);
This added the milliseconds to my datetime!

その他の回答 (2 件)

Peter Perkins
Peter Perkins 2016 年 8 月 3 日
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

Guillaume
Guillaume 2016 年 6 月 17 日
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

カテゴリ

Help Center および File ExchangeDates and Time についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by