Pregunta

I have a 13 digit string which is milliseconds since 1/1/1970. I need to convert it to a date time. The first step to do that is to get it into a useable number format. At 13 chars it's beyond the limits of ulong and long which have 10 digits max. I'm looking at int64 conversions. What's the best way to get this beast into a number format? I'm using c++ on a windows platform

Example "1382507187943" --> number? -- > datetime?

Thanks!

PART 2

Thank you guys! I am using c++ native. Thank you to poster 2 for the code.

I tried this and it worked as well where str contains the number and is a std::string:

__int64 u = _atoi64( str.c_str() );

PART 3

Actually, the 13 digit number does not fit in strtoul. I did this and got back the correct string.

__int64 u = _atoi64( str.c_str() );

time_t c;
//c = strtoul( "1382507187943", NULL, 0 );
c = u;
time(&c);
std::string s = ctime( &c );
¿Fue útil?

Solución

Either use strtull() or lop off the milliseconds yourself.

unsigned long long tms = strtoull("1382507187943", 10, 0);
time_t rawtime = tms/1000;
unsigned ms = tms%1000;

or

char buf[] = "1382507187943";
unsigned ms = strtoul(&buf[10], 10, 0);
buf[10] = '\0';
time_t rawtime = strtoul(buf, 10, 0);

then

struct tm * timeinfo;
time (&rawtime);
timeinfo = localtime (&rawtime);    

Otros consejos

If you are using a language that does not have native support for arbitrary precision arithmetic, you will need to add such support. A library such as GMP exposes an API for such math. It is likely that an implementation or binding exists for your language, as long as it is popular.

I created a binding for GMP in C# a while ago and am pretty sure it'll do what you want.

However, it is difficult to answer this question without knowing what language you are using.

time_t c;
c = strtoul( "1382507187943", NULL, 0 );
ctime( &c );

solution was from here

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top