Reputation: 39
I need to get the current date and time using C. However, I need it to be in hexadecimal format. Is their a function that returns the timestamp in hex or do I have to get the date and time and convert it to HEX? If so, does anyone have an example for the conversion in C?
Upvotes: 1
Views: 2854
Reputation: 21367
You can get a pointer to a tm
structure with localtime()
, and get the needed values from the fields. Then you can use sprintf()
to build a time string:
#include <stdio.h>
#include <time.h>
int main(void)
{
time_t raw_time = time(NULL);
struct tm *curr = localtime(&raw_time);
int year = curr->tm_year + 1900;
int month = curr->tm_mon + 1;
int day = curr->tm_mday;
int hour = curr->tm_hour;
int min = curr->tm_min;
int sec = curr->tm_sec;
char time_str[40];
sprintf(time_str, "%#x/%#x/%#x %#x:%#x:%#x",
year, month, day, hour, min, sec);
puts("Hex timestamp:");
puts(time_str);
sprintf(time_str, "%d/%d/%d %d:%d:%d",
year, month, day, hour, min, sec);
putchar('\n');
puts("Decimal timestamp:");
puts(time_str);
return 0;
}
Sample output:
Hex timestamp:
0x7e1/0x3/0x1f 0x14:0x2d:0x28
Decimal timestamp:
2017/3/31 20:45:40
Upvotes: 2