how to convert a date string to tm_wday in tm structure - c

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;
}

Related

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;
}

Incompatible types on assignment - C program for system date

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/

How to get current date and time and save it into char* array in proper format?

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.

How to Find a current day in c language?

I am able to get the current date but the output is like 9/1/2010,but my requirement is to get the current day like"Wednesday" not in form of integer value like 1.
My code is here.
#include <dos.h>
#include <stdio.h>
#include<conio.h>
int main(void)
{
struct date d;
getdate(&d);
printf("The current year is: %d\n", d.da_year);
printf("The current day is: %d\n", d.da_day);
printf("The current month is: %d\n", d.da_mon);
getch();
return 0;
}
Please help me to find the current day as Sunday,Monday.........
Thanks
Are you really writing for 16-bit DOS, or just using some weird outdated tutorial?
strftime is available in any modern C library:
#include <time.h>
#include <stdio.h>
int main(void) {
char buffer[32];
struct tm *ts;
size_t last;
time_t timestamp = time(NULL);
ts = localtime(&timestamp);
last = strftime(buffer, 32, "%A", ts);
buffer[last] = '\0';
printf("%s\n", buffer);
return 0;
}
http://ideone.com/DYSyT
The headers you are using are nonstandard. Use functions from the standard:
#include <time.h>
struct tm *localtime_r(const time_t *timep, struct tm *result);
After you call the function above, you can get the weekday from:
tm->tm_wday
Check out this tutorial/example.
There's more documentation with examples here.
As others have pointed out, you can use strftime to get the weekday name once you have a tm. There's a good example here:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{
char outstr[200];
time_t t;
struct tm *tmp;
t = time(NULL);
tmp = localtime(&t);
if (tmp == NULL) {
perror("localtime");
exit(EXIT_FAILURE);
}
if (strftime(outstr, sizeof(outstr), "%A", tmp) == 0) {
fprintf(stderr, "strftime returned 0");
exit(EXIT_FAILURE);
}
printf("Result string is \"%s\"\n", outstr);
exit(EXIT_SUCCESS);
}
Alternatively, if you insist on using your outdated compiler, there's a dosdate_t struct in <dos.h>:
struct dosdate_t {
unsigned char day; /* 1-31 */
unsigned char month; /* 1-12 */
unsigned short year; /* 1980-2099 */
unsigned char dayofweek; /* 0-6, 0=Sunday */
};
You fill it with:
void _dos_getdate(struct dosdate_t *date);
Use struct tm Example
strftime is certainly the right way to go. Of course you could do
char * weekday[] = { "Sunday", "Monday",
"Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
char *day = weekday[d.da_day];
I'm of course assuming that the value getdate() puts in the date struct is 0-indexed, with Sunday as the first day of the week. (I don't have a DOS box to test on.)

Resources