Datetime from Unix time miliseconds
조회 수: 3 (최근 30일)
이전 댓글 표시
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
채택된 답변
추가 답변 (2개)
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
댓글 수: 0
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
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!