Solved

C++ millisecond date and time into a string

Posted on 2008-06-12
17
13,519 Views
Last Modified: 2013-12-14
Hi all,

Having an __int64 value representing a millisecond time since January 1, 1970, 00:00:00 GMT, how can I convert it into a string representation of format yyyyMMddHHmmssSSS (milliseconds included) in the most efficient way? I'm well aware of struct tm* t = gmtime( &time ); , but how would I be able to get the date and the milliseconds into this as well? Is there a better way then just doing a division after division to extract the values? if not, can this be made with bitwise operations somehow?

This solution is to be done with C++, and be compatible with all compilers/OSs around. Should use UTC as timezone.

Thanks!

Stilgar.
0
Comment
Question by:_Stilgar_
  • 8
  • 8
17 Comments
 
LVL 53

Expert Comment

by:Infinity08
ID: 21774172
divide by 1000 to get the seconds, and then use strftime on that part :

        http://www.cplusplus.com/reference/clibrary/ctime/strftime.html

The milliseconds, you can get from the original value using modulo 1000, and append it to the result string of strftime.
0
 
LVL 53

Accepted Solution

by:
Infinity08 earned 500 total points
ID: 21774255
Something like :

__int64 millis;                            // <--- the time in milliseconds
 

char timestamp[20] = "";

time_t secs = millis / 1000;

tm *ptm = gmtime(&secs);

size_t len = strftime(timestamp, 20, "%Y%m%d%H%M%S", ptm);

unsigned int ms = millis % 1000;

sprintf(timestamp + len, "%03u", ms);
 

std::cout << timestamp << std::endl;

Open in new window

0
 
LVL 11

Expert Comment

by:DeepuAbrahamK
ID: 21776972
>>time_t secs = millis / 1000;
How do you get the millis?

0
 
LVL 53

Expert Comment

by:Infinity08
ID: 21777031
>> How do you get the millis?

That was part of the question :

>> Having an __int64 value representing a millisecond time since January 1, 1970, 00:00:00 GMT
0
 
LVL 14

Author Comment

by:_Stilgar_
ID: 21779355
Thanks Infinity08. 2 follow-up questions:

1) Are there any adjustments required for DST, or gmtime always returns the correct UTC (GMT) time, no matter what, and regardless the locale of the calling application ?

2) What is the fastest way for the reverse operation (_tcsftime formatted string to an __int64 - please tell me there's a function for that :) ).

Stilgar.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 21779589
>> Are there any adjustments required for DST

Depends what you want. The tm struct returned by gmtime has a tm_isdst field that handles this.

gmtime will return the time for the GMT timezone, and without DST taken into account (even if the time is in the summer). For example, I am at GMT+1, and another +1 for DST, so GMT+2. gmtime called for the current time will return The current local time minus 2 hours, so 14:57 instead of 16:57.

        http://www.cplusplus.com/reference/clibrary/ctime/tm.html


>> What is the fastest way for the reverse operation

I don't know if there's a faster way on your platform, but you can always fill a tm struct with the values parsed from the timestamp string. Then use mktime to return the time_t value. Multiply that by 1000 and add the millisecond.

        http://www.cplusplus.com/reference/clibrary/ctime/mktime.html
0
 
LVL 14

Author Comment

by:_Stilgar_
ID: 21779730
>> Depends what you want

I want to always get the correct GMT value, no matter what. According to MSDN tm_isdst is Always 0 for gmtime. Now it is DST period in GMT as well as in my location, and gmtime returned the correct time for an __int64 generated using ftime(). What does this mean - that in periods when the user location is not in DST and GMT is, or vice versa, time strings based on the function above will return wrong times?

I will try mktime, thanks. Will this do to reset it so I will not need to set all values in cases where I need to fill just the year for example?

            tm s_time;
            memset(&s_time, 0, sizeof(s_time));
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 21779945
>> Now it is DST period in GMT as well as in my location

Yes, but that means that Greenwich is actually in GMT+1 due to DST. The real base time is GMT, without DST.

ftime should get the GMT time without DST. That's the value you want. If you want to add an hour for DST, then you can do so. If you have to change the timezone, you can add/subtract hours (or let functions like localtime handle that).

So, basically, the time in seconds (the time_t value) is the GMT time (no DST), which you can then show any way you like. From what I understand of your requirements, you simply need gmtime, which will show the time as it is, without taking into account DST or the local timezone.



>> Will this do to reset it so I will not need to set all values in cases where I need to fill just the year for example?

That should be fine, yes. Except for the day of the month (tm_mday), which is 1 minimum.
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 14

Author Comment

by:_Stilgar_
ID: 21893200
Sorry about the long silence, things have been a bit hectic lately. Will get a closure on this during the next days...
0
 
LVL 14

Author Comment

by:_Stilgar_
ID: 21906860
Is strftime / _tcsftime compatible with linux/mac?
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 21906905
>> Is strftime / _tcsftime compatible with linux/mac?

strftime is in the C standard library, so that shouldn't give you problems (as long as you're using a standards compliant compiler).

_tcsftime is a Windows function, so it's likely that it won't be available on other platforms. You don't need to use it though (see the code I posted).
0
 
LVL 14

Author Comment

by:_Stilgar_
ID: 21906979
So wcsftime should be in the standard library as well right? so I just need to use #ifndef _tcsftime and define it for Linux / Mac enviroments?
0
 
LVL 14

Author Comment

by:_Stilgar_
ID: 21906992
I want to support TCHAR with this, not just char, thats why I'm trying _tcsftime...
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 21907079
Yes, wcsftime is standard. It works on wchar_t though, not TCHAR.

        http://www.opengroup.org/onlinepubs/007908799/xsh/wcsftime.html


>> so I just need to use #ifndef _tcsftime and define it for Linux / Mac enviroments?

Why not simply use wcsftime on all systems ?
0
 
LVL 14

Author Comment

by:_Stilgar_
ID: 21907160
_tcsftime and TCHAR are barely macros that will interpret as strftime and char for DBCS/MBCS builds and as wcsftime and wchar_t for Unicode builds by the compiler. I'm not sure why only VS has _tcsftime declared and Linux/mac compilers don't?

I want to use _tcsftime to support both Unicode and non-Unicode builds.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 21907272
>> I'm not sure why only VS has _tcsftime declared and Linux/mac compilers don't?

Because it's an MS extension ;) Ask them why they didn't stick with the standards heh.
0
 
LVL 14

Author Closing Comment

by:_Stilgar_
ID: 31466761
Thanks for all your help, and sorry for the time it took me to get a closure...
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Programmer's Notepad is, one of the best free text editing tools available, simply because the developers appear to have second-guessed every weird problem or issue a programmer is likely to run into. One of these problems is selecting and deleti…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
THe viewer will learn how to use NetBeans IDE 8.0 for Windows to perform CRUD operations on a MySql database.
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now