Get the datetime in C - c

I know that with the usage of ctime like this
time_t now;
time(&now);
fprintf(ft,"%s",ctime(&now));
returns me the datetime in this way
Tue Jun 18 12:45:52 2013
My question is if there is something similar with ctime to get the time in this format
2013/06/18 10:15:26

Use strftime
#include <stdio.h>
#include <time.h>
int main()
{
struct tm *tp;
time_t t;
char s[80];
t = time(NULL);
tp = localtime(&t);
strftime(s, 80, "%Y/%m/%d %H:%M:%S", tp);
printf("%s\n", s);
return 0;
}

See the manpages for localtime and strftime. The first function converts the timestamp in a structure with the date/time elements, the second converts that to a string using a format string.

Broken-down time is stored in the structure tm which is defined in as follows:
struct tm {
int tm_sec; /* seconds */
int tm_min; /* minutes */
int tm_hour; /* hours */
int tm_mday; /* day of the month */
int tm_mon; /* month */
int tm_year; /* year */
int tm_wday; /* day of the week */
int tm_yday; /* day in the year */
int tm_isdst; /* daylight saving time */
};
It is possible to display individual variables in the format we desire to achieve.

#include <stdio.h>
#include <time.h>
int main(void){
FILE *ft = stdout;
char outbuff[32];
struct tm *timeptr;
time_t now;
time(&now);
timeptr = localtime(&now);
strftime(outbuff, sizeof(outbuff), "%Y/%m/%d %H:%M:%S", timeptr);//%H:24 hour
fprintf(ft,"%s", outbuff);
return 0;
}

Related

How to add days to a datetime string?

I want to add N number of days to the datetime string s. I tried to do that by extracting year,month,day fields separately but it does not work.
#include<stdio.h>
#include<time.h>
int main
{
time_t t = time(NULL);
struct tm *tm = localtime(&t);
char s[64];
strftime(s, sizeof(s), "%Y-%m-%d", tm); //gives date in yy-mm-dd format
printf("%s",s); //prints the date
}
Add N days to the tm_mday member and then normalize with mktime().
It is not practical for a direct string edit #kaylum.
time_t mktime(struct tm *timeptr); returns a time_t conversion of *timeptr, yet that value is ignored below other than to check for errors. It is the side effect that the function adjusts the members to their usual primary range that is desired.
#include<stdio.h>
#include<time.h>
// next week
#define N 7
int main() {
time_t t = time(NULL);
struct tm *tm = localtime(&t);
tm->tm_mday += N;
if (mktime(tm) == -1) {
printf("Calendar time cannot be represented.\n");
} else {
char s[64];
strftime(s, sizeof s, "%Y-%m-%d", tm);
printf("%s\n", s); // Print the date.
}
}
Output on March 25th. Notice tm_mday and tm_mon have been adjusted.
2017-04-01

How can i get the current time in C with d/m/y format?

Which function can return current datetime with d/m/y format in C language?
EDIT:
here is my code:
#include <stdio.h>
#include <time.h>
int main()
{
time_t tmp_time;
struct tm * info;
time ( &tmp_time );
info = localtime ( &tmp_time );
printf ( "%s", asctime (info) );
}
this returns to me something like that Thu Jan 26 13:08:01 2017 and i would like to return 26/01/17 or 26/01/2017
Like this:
int main ()
{
time_t rawtime;
struct tm * currentTime;
time ( &rawtime );
currentTime = localtime ( &rawtime );
printf ( "%d/%d/%d", currentTime->tm_mday, currentTime->tm_mon+1, currentTime->tm_year+1900);
return 0;
}
Be careful, months are indexed since 0, and year is since 1900 in tm struct.
Perhaps like this:
#include <stdio.h>
#include <time.h>
int main()
{
time_t t = time(0);
if((time_t)-1 == t){
perror(0);
exit(1);
}
char buf[64];
struct tm tdata;
//I believe the 2 calls below should always succeed
//in this context
localtime_r(&t, &tdata);
strftime(buf, sizeof(buf), "%d/%m/%y", &tdata);
puts(buf);
}
The localtime(3) manpage says strftime is the recommended way to do it, and the strftime(3) manpage provides a similar example.
You can do it like this
#include <time.h>
#include <stdio.h>
int main(void)
{
time_t mytime = time(NULL);
struct tm date = *localtime(&mytime);
printf("now: %d/%d/%d\n", date.tm_mday,date.tm_mon + 1,date.tm_year +1900 );
return 0;
}
if you want to make it a function send the date as a parameter and return a int array holds day month and year

how to display datetime using C Programming

I have to display date and time separately using gettime() and getdate() in C programming language. The code I have written only displays date and time on same line. I want this code to be done using only core C not in a windows format.The editor I am using is Visual Studio 2008
Below I have post my code which only shows date time on a single line.
#include "stdafx.h"
#include <conio.h>
#include <stdio.h>
#include <time.h>
char *gettime();
int_main(int argc,_TCHAR* argv[])
{
printf("The time is %s\n",gettime());
getch();
return 0;
}
char *gettime()
{
time_t t;
tm b;
time(&t);
return ctime(&t);
}
You can use localtime/gmtime
struct tm * timeinfo;
timeinfo = localtime (&t);
And work with tm structure components as you need, also you can use strfrtime format function if you need only print date and time.
Main function is the same for all the different ways:
#include <stdio.h>
#include <time.h>
#include <string.h>
char * gettime();
char * getdate();
int main()
{
printf("The time is %s\n", gettime());
printf("The date is %s\n", getdate());
return 0;
}
One way you could do it is with manipulating the strings coming back from ctime() function. We know they are built in a similar way, the 1st 12 chars are week-day, month, month-day, then comes 8 chars of time, then finally the year. You could create functions like this:
char * gettime()
{
time_t t;
//use static so not to save the var in stack, but in the data/bss segment
//you can also make it a global scope, use dynamic memory allocation, or
//use other methods as to prevent it from being erased when the function returns.
static char * time_str;
time(&t);
time_str = ctime(&t) + 11;
time_str[9] = 0; //null-terminator, eol
return time_str;
}
char * getdate()
{
time_t t;
static char * date_str;
static char * year;
time(&t);
date_str = ctime(&t) + 4;
date_str[6] = 0;
year = date_str + 15;
year[5] = 0;
strcat(date_str, year);
return date_str;
}
The second way to do this is using localtime() function to create a tm-struct, and then extract what you need from it.
char * gettime()
{
time_t t;
struct tm *info;
static char time_str[10];
time(&t);
info = localtime(&t);
sprintf(time_str,"%d:%d:%d",(*info).tm_hour, (*info).tm_min, (*info).tm_sec);
return time_str;
}
char * getdate()
{
time_t t;
struct tm *info;
static char date_str[12];
time(&t);
info = localtime(&t);
sprintf(date_str,"%d/%d/%d",(*info).tm_mday, (*info).tm_mon+1, (*info).tm_year+1900);
return date_str;
}
You can make it a bit more clean using the strftime() function:
char * gettime()
{
time_t t;
struct tm *info;
static char time_str[10];
time(&t);
info = localtime(&t);
strftime(time_str, 10, "%S:%M:%H",info);
return time_str;
}
char * getdate()
{
time_t t;
struct tm *info;
static char date_str[12];
time(&t);
info = localtime(&t);
strftime(date_str, 12, "%d:%m:%Y",info);
return date_str;
}

how to get date and time in the format 2013-01-11 23:34:21?

In my C program, how can I get the date and time in the format 2013-01-11 23:34:21?
I tried
time_t now;
time(&now);
printf("%s", ctime(&now));
But it's giving it like Fri Jan 11 23:50:33 2013...
Thanks
You could use the strftime() function from <time.h>
#include <time.h>
#include <stdio.h>
int main() {
time_t now;
time(&now);
struct tm* now_tm;
now_tm = localtime(&now);
char out[80];
strftime (out, 80, "Now it's %Y-%m-%d %H:%M:%S.", now_tm);
puts(out);
}
Output
Now it's 2013-01-12 10:33:13.
Try strftime from time.h:
char timeString[20];
time_t t;
struct tm tmp;
t = time(NULL);
// TODO: Error checking if (t < 0)
tmp = localtime_r(&t, &tmp);
// TODO: Error checking if tmp == NULL
strftime(timeString, sizeof(timeString), "%Y-%m-%d %H:%M:%S", tmp));
// TODO: Error checking if returned number == sizeof(timeString)-1

How to print time in format: 2009‐08‐10 18:17:54.811

What's the best method to print out time in C in the format 2009‐08‐10 
18:17:54.811?
Use strftime().
#include <stdio.h>
#include <time.h>
int main()
{
time_t timer;
char buffer[26];
struct tm* tm_info;
timer = time(NULL);
tm_info = localtime(&timer);
strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info);
puts(buffer);
return 0;
}
For milliseconds part, have a look at this question. How to measure time in milliseconds using ANSI C?
The above answers do not fully answer the question (specifically the millisec part). My solution to this is to use gettimeofday before strftime. Note the care to avoid rounding millisec to "1000". This is based on Hamid Nazari's answer.
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <math.h>
int main() {
char buffer[26];
int millisec;
struct tm* tm_info;
struct timeval tv;
gettimeofday(&tv, NULL);
millisec = lrint(tv.tv_usec/1000.0); // Round to nearest millisec
if (millisec>=1000) { // Allow for rounding up to nearest second
millisec -=1000;
tv.tv_sec++;
}
tm_info = localtime(&tv.tv_sec);
strftime(buffer, 26, "%Y:%m:%d %H:%M:%S", tm_info);
printf("%s.%03d\n", buffer, millisec);
return 0;
}
time.h defines a strftime function which can give you a textual representation of a time_t using something like:
#include <stdio.h>
#include <time.h>
int main (void) {
char buff[100];
time_t now = time (0);
strftime (buff, 100, "%Y-%m-%d %H:%M:%S.000", localtime (&now));
printf ("%s\n", buff);
return 0;
}
but that won't give you sub-second resolution since that's not available from a time_t. It outputs:
2010-09-09 10:08:34.000
If you're really constrained by the specs and do not want the space between the day and hour, just remove it from the format string.
Following code prints with microsecond precision. All we have to do is use gettimeofday and strftime on tv_sec and append tv_usec to the constructed string.
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
int main(void) {
struct timeval tmnow;
struct tm *tm;
char buf[30], usec_buf[6];
gettimeofday(&tmnow, NULL);
tm = localtime(&tmnow.tv_sec);
strftime(buf,30,"%Y:%m:%dT%H:%M:%S", tm);
strcat(buf,".");
sprintf(usec_buf,"%dZ",(int)tmnow.tv_usec);
strcat(buf,usec_buf);
printf("%s",buf);
return 0;
}
trick:
int time_len = 0, n;
struct tm *tm_info;
struct timeval tv;
gettimeofday(&tv, NULL);
tm_info = localtime(&tv.tv_sec);
time_len+=strftime(log_buff, sizeof log_buff, "%y%m%d %H:%M:%S", tm_info);
time_len+=snprintf(log_buff+time_len,sizeof log_buff-time_len,".%03ld ",tv.tv_usec/1000);
You could use strftime, but struct tm doesn't have resolution for parts of seconds. I'm not sure if that's absolutely required for your purposes.
struct tm tm;
/* Set tm to the correct time */
char s[20]; /* strlen("2009-08-10 18:17:54") + 1 */
strftime(s, 20, "%F %H:%M:%S", &tm);
None of the solutions on this page worked for me, I mixed them up and made them working with Windows and Visual Studio 2019, Here's How :
#include <Windows.h>
#include <time.h>
#include <chrono>
static int gettimeofday(struct timeval* tp, struct timezone* tzp) {
namespace sc = std::chrono;
sc::system_clock::duration d = sc::system_clock::now().time_since_epoch();
sc::seconds s = sc::duration_cast<sc::seconds>(d);
tp->tv_sec = s.count();
tp->tv_usec = sc::duration_cast<sc::microseconds>(d - s).count();
return 0;
}
static char* getFormattedTime() {
static char buffer[26];
// For Miliseconds
int millisec;
struct tm* tm_info;
struct timeval tv;
// For Time
time_t rawtime;
struct tm* timeinfo;
gettimeofday(&tv, NULL);
millisec = lrint(tv.tv_usec / 1000.0);
if (millisec >= 1000)
{
millisec -= 1000;
tv.tv_sec++;
}
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, 26, "%Y:%m:%d %H:%M:%S", timeinfo);
sprintf_s(buffer, 26, "%s.%03d", buffer, millisec);
return buffer;
}
Result :
2020:08:02 06:41:59.107
2020:08:02 06:41:59.196

Resources