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
Related
I'm trying to parse the system date by calling struct tm and getting the current time before parsing into separate day, month, year. Here is my code at hte moment:
/* Parses a system date structure 'system_date' into a structure date 'parsed_date'.*/
int parse_system_date(struct tm system_date, date * parsed_date) {
time_t ts;
struct tm t;
ts = time(NULL);
t = localtime(&ts);
/* scan the year, month and year from the input string*/
//printf("Current Date: %d/%d/%d\n",
// current_time->tm_mday, current_time->tm_mon + 1, current_time->tm_year + 1900);
const int ret = sscanf(system_date, "%d/%d/%d",
&parsed_date->(tm_mday),
&parsed_date->(tm_month + 1),
&parsed_date->(tm_year + 1900));
return ret;
}
And it's being called from the main by:
struct tm t;
char system_date[20];
fgets(system_date, 20, stdin);
parse_system_date(system_date, &t);
printf("Today's date is: %s\ndd = %d, mm = %d, yy = %d\n", system_date, t.tm_mday, t.tm_mon, t.tm_year);
I'm getting the error:
date.h:30: error: incompatible types in assignment
In the line:
t = localtime(&ts);
And:
date.h:39: error: incompatible type for argument 1 of ‘sscanf’
for the line:
&parsed_date->(tm_mday).
Any ideas? Thanks for the help! Just to note: I'm a beginner programmer but trying to immerse myself entirely as I just started PhD that deals mainly in programming so I'm a total newbie.
The function localtime is documented to return a struct tm* (that is, a Pointer to a Structure).
You are trying to assign that to variable t, which has type struct tm (note: no pointer in there).
You cannot assign a pointer to a non-pointer.
I recommend changing to:
int parse_system_date(struct tm system_date, date * parsed_date) {
struct tm* pt;
[....]
pt = localtime(&ts);
Now I'll leave it up to you to look up the documentation of sscanf, and YOU tell US what param #1 to sscanf should be, and what you are actually passing.
system_date is char * in main and struct tm system_date in the function call.
Change the function call to
int parse_system_date(char *system_date, date * parsed_date)
As man localtime states:
struct tm *localtime(const time_t *timep);
Your t in t = localtime(&ts) is a struct tm not struct tm*, and localtime returns a pointer.
For second thing you didn't really show us how does parsed_date look (no definition of date structure). Also system_date is a struct tm then why would you expect it would be taken as const char* in sscanf?
A working solution for you
#include <stdio.h>
#include <time.h>
/* Parses a system date structure 'system_date' into a structure date 'parsed_date'.*/
void parse_system_date(char* system_date, struct tm **parsed_date) {
time_t ts;
int ret;
int year;
int month;
int day;
ts = time(NULL);
*parsed_date = localtime(&ts);
sscanf(system_date,"%d/%d/%d",&day,&month,&year);
(*parsed_date)->tm_mday = day;
(*parsed_date)->tm_mon = month + 1;
(*parsed_date)->tm_year = year + 1900;
}
int main(){
struct tm* t;
char system_date[20]={'\0'};
fgets(system_date, 20, stdin);
parse_system_date(system_date, &t);
printf("Today's date is: %s\ndd = %d, mm = %d, yy = %d\n", system_date, t->tm_mday, t->tm_mon, t->tm_year);
return 0;
}
Input : 11/03/2014
Output: Today's date is: 11/03/2014
dd = 11, mm = 4, yy = 3914
I modified your code to get a meaningful output but I did not understand the requirement of your program. Because you have few unused variables and operations like,
time_t ts;
struct tm t;
ts = time(NULL);
t = localtime(&ts);
and function signature also wrong.
localtime returns a pointer to the struct:
http://www.cplusplus.com/reference/ctime/localtime/
I know how to get current date & time and save it into an array. But I would like to print it in format: dd.mm.YYY_HH:MM:ss. How can I change my code to achieve this?
#include <stdio.h>
#include <time.h>
char *datetime()
{
char *array = (char*)malloc(sizeof(char)*25);
time_t result;
result = time(NULL);
sprintf(array, "%s", asctime(localtime(&result)));
array[25] = '\0';
return array;
}
int main(void)
{
// prints Sat Aug 3 18:39:07 2013
printf("%s", datetime());
// how to print:
// 03.08.2013_18:39:07
// ?
return(0);
}
Using strftime - see here
This will look like this -
time_t rawtime;
time (&rawtime);
struct tm *timeinfo = localtime (&rawtime);
strftime(array, sizeof(array)-1, "%d.%m.%y_%H:%M:%S", timeinfo);
You can use strftime function:
http://www.gnu.org/software/libc/manual/html_node/Formatting-Calendar-Time.html
strftime is described in C99 Standard in 7.23.3.5.
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;
}
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
I have a date string format say like "2010-03-01" and I want to get the "tm_wday" equivalent of it say like Monday, Tuesday ...
Could someone give me a hint on how to achieve this in c?
Check the strptime() function:
char *strptime(const char *s, const char *format, struct tm *tm);
The strptime() function is the converse function to strftime(3) and converts the
character string pointed to by s to values which are stored in the tm structure
pointed to by tm, using the format specified by format.
Use mktime() to calculate the weekday.
#include <memory.h>
#include <stdio.h>
#include <time.h>
int main(void) {
const char *p = "2010-03-01";
struct tm t;
memset(&t, 0, sizeof t); // set all fields to 0
if (3 != sscanf(p,"%d-%d-%d", &t.tm_year, &t.tm_mon, &t.tm_mday)) {
; // handle error;
}
// Adjust to struct tm references
t.tm_year -= 1900;
t.tm_mon--;
// Calling mktime will set the value of tm_wday
if (mktime(&t) < 0) {
; // handle error;
}
printf("DOW(%s):%d (0=Sunday, 1=Monday, ...)\n", p, t.tm_wday);
// DOW(2010-03-01):1 (0=Sunday, 1=Monday, ...)
return 0;
}