Abdul Manaf
Abdul Manaf

Reputation: 4993

Convert current milliSecond to time format using C

i need to convet current time in milliseconds to human readable time format. I have following code

#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <sys/time.h>
#include <time.h>

int Cnvrt_To_Time_Frmt(char *Epochval)
{
    unsigned long epoch = 0;
    time_t tt = 0;
    char timestamp[64],usec_buf[20];
    if (!sscanf(Epochval, "%lu", &epoch))
    {
        return 1;
    }
    tt = epoch;

    strftime(timestamp, 64, "%c", localtime(&tt));
    printf("%s\n",timestamp);
    return 0;
}

int main()
{
    uint64_t Epoch_time=1468496250207;
    char str_ms[256];
    sprintf(str_ms, "%llu", (Epoch_time/1000));
    Cnvrt_To_Time_Frmt(str_ms);

}

It produce result : Thu Jul 14 17:07:30 2016.

But i need to print result with milli seconds. like Thu Jul 14 17:07:30:40 2016.(17 hour,07 minute, 30 second, 40 milliSecond)

How it will be possible?

Upvotes: 3

Views: 6478

Answers (5)

wryan
wryan

Reputation: 1521

This example program will both retrieve the current timestamp from they system OS, and print it out in human readable format. It is similar to @user:2410359 answer, but a little more concise.

#include <stdio.h>
#include <time.h>
#include <sys/time.h>

/* 
 * timestamp - read and print the current timestamp
 * Wade Ryan 2020-09-27
 * compile using: g++ timestamp.cpp -o timestamp
 */ 

int main(int argc, char **argv) {
    char   timestamp[24];
    struct timeval currentTime;
    struct tm      ts;

    gettimeofday(&currentTime, NULL);

    long long epoch  =  (unsigned long long)(currentTime.tv_sec) * 1000 +
                        (unsigned long long)(currentTime.tv_usec) / 1000;
        
    strftime(timestamp, sizeof(timestamp), "%F %T", localtime(&currentTime.tv_sec));

    printf("epoch %lld ms :: %s.%03ld\n", epoch, timestamp, currentTime.tv_usec/1000);

}

Example output:

epoch 1601259041504 ms :: 2020-09-27 21:10:41.504

Upvotes: 0

chux
chux

Reputation: 153338

... need to print result with milli seconds. ... How it will be possible?

Take it step by step

uint64_t Epoch_time=1468496250207;

// Break time into a whole number of seconds and ms fraction
time_t t_unix = Epoch_time/1000;
unsigned t_ms = Epoch_time%1000;

// Convert to YMD HMS structure
struct tm tm = *localtime(&t_unix);

// Form left portion of string
char left[64];
strftime(left, sizeof left, "%a %b %d %H:%M", &tm);

// Form right portion of string
char right[20];
strftime(right, sizeof right, "%Y", &tm);

// Put together with ms
char timestamp[64];
snprintf(timestamp, sizeof timestamp, "%s:%u %s", left, t_ms, right);

// Thu Jul 14 17:07:30:40 2016
// Print as needed
puts(timestamp);

Robust code would add error checking with each function's return value.


[edit] Evidently OP's time stamp's last 3 digits are a fraction / 512.

unsigned t_fraction = Epoch_time%1000;
...
snprintf(timestamp, sizeof timestamp, "%s:%02u %s", left, t_fraction*100/512, right);

Upvotes: 0

Mark Davydov
Mark Davydov

Reputation: 447

I don't have 50 reps yet so I can't comment so I will write my suggestion as an answer here.

You can use the other guys suggestions they are pretty good or you can make your own struct and a function that converts the mili seconds into time , by using basic math functions.

Make a struct that contains dayOfWeek , month , dayOfMonth , hour, minute, second , milliSecond , year. Make a convertFunction that will receive a value of milliSeconds that need to be converted to your struct format. Maybe its not the best way to do it , but if you don't find a way of using existing libraries , make your own .

Upvotes: 0

a3f
a3f

Reputation: 8657

Use this as format string:

strftime(timestamp, 64, "%a %b %d %H:%M:%S.XXX %Y", localtime(&tt));

The XXX will be copied as-is into the time string. Then in main, you can overwrite the Xs with the millisecond count.

sprintf(&timestamp[20], "%03u", (unsigned)Epoch_time%1000);
timestamp[23] = ' '; // restore the NUL to space again

After that, refactor your code so the divisions and remainder operations are done inside Cnvrt_To_Time_Frmt. You could use this as prototype:

int msecs_tostr(char *buffer, const char *msecs_since_epoch);

Upvotes: 1

mvidelgauz
mvidelgauz

Reputation: 2214

Type time_t by its definition doesn't represent time with milliseconds resolution, function localtime returns pointer to struct tm which does not include milliseconds, function strftime is not designed to produce strings with milliseconds.

If you need time with milliseconds you can use timeb stucture with its associated ftime function if those are supported by your tool-chain.

Upvotes: 2

Related Questions