I have this unix timestamp which when converted using ctime shows as Thu Mar 26 15:30:26 2007
, but I need only Thu Mar 26 2007
.
How do I change or truncate to eliminate the time (HH:MM:SS)?
From the manpage of strptime()
:
The following example demonstrates the use of strptime()
and strftime()
.
#include <stdio.h>
#include <time.h>
int main() {
struct tm tm;
char buf[255];
strptime("2001-11-12 18:31:01", "%Y-%m-%d %H:%M:%S", &tm);
strftime(buf, sizeof(buf), "%d %b %Y %H:%M", &tm);
puts(buf);
return 0;
}
Adjust to your own needs.
Since you've got a time_t
value, you can use localtime()
and strftime()
:
#include <time.h>
#include <stdio.h>
int main(void)
{
time_t t = time(0);
struct tm *lt = localtime(&t);
char buffer[20];
strftime(buffer, sizeof(buffer), "%a %b %d %Y", lt);
puts(buffer);
return(0);
}
Alternatively, if you feel you must use ctime()
, then:
#include <time.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
time_t t = time(0);
char buffer[20];
char *str = ctime(&t);
memmove(&buffer[0], &str[0], 11);
memmove(&buffer[11], &str[20], 4);
buffer[15] = '\0';
puts(buffer);
return(0);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.