I'm a beginner in C.
Is there any datatype for dates?
In C we have for working with time, is there one for dates too?
How can I calculate difference between two dates?
Yes,the standard library C Time Library contains structures and functions you want.You can use struct tm to store date and difftime to get the difference.
Is there any datatype for save dates?
No, although for dates in the range "now plus or minus a few decades" you could use time_t or struct tm containing the datetime at (for example) midnight on the relevant day. Alternatively you could look into a thing called the "Julian day": compute that and store it in whatever integer type you like.
Is there any library for C too?
The standard functions all relate to date/times rather than just dates: mktime, localtime, gmtime.
How can I calculate different between two date
Once you have it in a time_t you can subtract the two and divide by 86400. Watch out, though, since "midnight local time" on two different days might not be an exact multiple of 24 hours apart due to daylight savings changes.
If you need a calendar that extends beyond the range of time_t on your implementation then you're basically on your own. If time_t is 64 bits then that's more than the age of the universe, but if time_t is 32 bits it's no good for history. Or pension planning, even. Historical applications have their own demands on calendars anyway (Julian calendar, calendars completely unrelated to Gregorian).
The standard C library options for dates and times are pretty poor and loaded with caveats and limitations. If at all possible, use a library such as Gnome Lib which provides GDate and numerous useful date and time functions. This includes g_date_days_between() for getting the number of days between two dates.
The rest of this answer will restrict itself to the standard C library, but if you don't have to limit yourself to the standard, don't torture yourself. Dates are surprisingly hard.
Is there any datatype for dates?
struct tm will serve. Just leave the hour, minutes, and seconds at 0.
Simplest way to ensure all the fields of struct tm are properly populated is to use strptime.
struct tm date;
strptime( "2017-03-21", "%F", &date );
puts( asctime(&date) ); // Mon Mar 21 00:00:00 2017
But that's not a great way to store dates. It turns out it's better to use Julian Days (see below).
In C we have for working with time, is there one for dates too?
If you're referring to time_t, that is also for date-times. It's the number of seconds since "the epoch" which is 1970-01-01 00:00:00 UTC on POSIX systems, but not necessarily others. Unfortunately its safe range is only 1970 to 2037, though any recent version of an operating system will have greatly expanded that range.
How can I calculate difference between two dates?
Depends on what you want. If you want the number of seconds, you could convert the struct tm to time_t using mktime and then use difftime, but that's limited to the 1970-2037 safe range of time_t.
int main() {
struct tm date1, date2;
strptime( "2017-03-21", "%F", &date1 );
strptime( "2018-01-20", "%F", &date2 );
printf("%.0lf\n", difftime(mktime(&date1), mktime(&date2)));
}
If you want the number of days, you'd convert the dates into Julian days, the number of days since November 24, 4714 BC, and subtract. While that might seem ridiculous, this relatively simple formula takes advantage of calendar cycles and only uses integer math.
// The formulas for a and m can be distilled down to these tables.
int Julian_A[12] = { 1, 1, 0 };
int Julian_M[12] = { 10, 11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int julian_day( struct tm *date ) {
int a = Julian_A[date->tm_mon];
int m = Julian_M[date->tm_mon];
int y = date->tm_year + 1900 + 4800 - a;
return date->tm_mday + ((153*m + 2) / 5) + 365*y + y/4 - y/100 + y/400 - 32045;
}
int main() {
struct tm date1, date2;
strptime( "2017-03-21", "%F", &date1 );
strptime( "2018-01-20", "%F", &date2 );
// 305 days
printf("%d days\n", julian_day(&date2) - julian_day(&date1));
}
There are other simple formulas for converting between Julian Dates and calendar dates.
Getting diffs in years, months, and days is difficult because of the number of days in a month varies by month and year, and because it has to be normalized. For example, you wouldn't say 2 years, -1 months, 2 days. You'd say 1 year, 11 months, 29 days (or maybe 28, depends on the month). For this reason, do date math in Julian Days whenever possible.
To get an idea of what's involved, PHP implements this as date_diff. Have a look at the amount of C code required.
Is there any datatype for dates?
No, inbuilt datatype in C , you have to defined user-defined data type.
How can I calculate difference between two dates?
You may try this:
struct dt
{
int dd;
int mm;
int yy;
};
typedef dt date;
In main() you need to declare three variables for type data.
In following example today difference,
for example you wants to take difference between current date (c_date) and date of birth (dob)
date dob,c_date,today;
if(c_date.dd>=dob.dd)
today.dd = c_date.dd-dob.dd;
else
{
c_date.dd+=30;
c_date.mm-=1;
today.dd = c_date.dd-dob.dd;
}
if(c_date.mm>=dob.mm)
today.mm = c_date.mm-dob.mm;
else
{
c_date.mm+=12;
c_date.yy-=1;
today.mm = c_date.dd-dob.mm;
}
today.yy = c_date.yy-dob.yy;
In today you have difference between two dates.
There is one more way: double difftime (time_t end, time_t beginning);
Read this answers:
1. How to compare two time stamp in format “Month Date hh:mm:ss"
2. How do you find the difference between two dates in hours, in C?
You can create a struct named date having following fields
typedef struct
{
int day;
int month;
int year;
}date;
It's just a blueprint what you want , now make and object of date and work accordingly.
To find the difference ,write a function to take a difference between day month and year of the both stucts respectively.
You have to define a date struct:
typedef struct date {
int day;
int month;
int year;
} Date;
And then define a simple date_compare() method:
int date_compare(Date *date1, Date *date2) {
if (date1->year != date2->year)
return (date1->year - date2->year);
if (date1->month != date2->month)
return (date1->month - date2->month);
return (date1->day - date2->day);
}
/* Version 3 (better)
Date Difference between the two dates in days
like VBA function DateDiff("d", date1, date2)
in case of Gregorian. Same basic principle you
can translate in lot of other languages. This
is complete C code with date validity control.
*/
#include<stdio.h>
void main(){
long d1,m1,y1,d2,m2,y2;
printf("Enter first date day, month, year\n");
scanf("%d%d%d",&d1,&m1,&y1);
printf("Enter second date day, month, year\n");
scanf("%d%d%d",&d2,&m2,&y2);
if((IsValid(d1,m1,y1)==0)||(IsValid(d2,m2,y2)==0)){
printf("Invalid date detected\n");
}else{
d1=DatDif(d1,m1,y1,d2,m2,y2);
printf("\n\n Date difference is %d days\n",d1);
}
}// end main
long DatDif(d1,m1,y1,d2,m2,y2)
{ long suma;
suma=rbdug(d2,m2,y2) - rbdug(d1,m1,y1);
if(y1 != y2){
if(y1 < y2){
suma+=Godn(y1,y2);
}else{
suma-=Godn(y2,y1);
}
}
return(suma);
}// end DatDif
long Godn(yy1,yy2)
{ long jj,bb;
bb=0;
for(jj=yy1;jj<yy2;jj++){
bb+=365;
if(((((jj%400)==0)||((jj%100)!=0))
&&((jj%4)==0))) bb+=1;
}
return(bb);
}// end Godn
//Day of the Year
long rbdug(d,m,y)
{ long a,r[13];
r[1] = 0; r[2] = 31; r[3] = 59;
r[4] = 90; r[5] = 120; r[6] = 151;
r[7] = 181; r[8] = 212; r[9] = 243;
r[10]= 273; r[11]= 304; r[12]= 334;
a=r[m]+d;
if(((((y%400)==0)||((y%100)!=0))
&&((y%4)==0))&&(m>2)) a+=1;
return(a);
}//end rbdug
//date validity
long IsValid(dd,mm,yy)
{ long v[13];
if((0 < mm) && (mm < 13)){
v[1] = 32; v[2] = 29; v[3] = 32;
v[4] = 31; v[5] = 32; v[6] = 31;
v[7] = 32; v[8] = 32; v[9] = 31;
v[10]= 32; v[11]= 31; v[12]= 32;
if(((((yy%400)==0)||((yy%100)!=0))
&&((yy%4)==0))) v[2]+=1;
if((0 < dd) && (dd < v[mm])){
return(1);
}else{
return(0);
}
}else{
return(0);
}
}//end IsValid
/* Version 4 ( 100 % correct):
Proleptic Gregorian date difference in days.
Date Difference between the two dates in days
like VBA function DateDiff("d", date1, date2)
and better (without limitations of DateDiff)
in case of Gregorian. Same basic principle you
can translate in lot of other languages. This
is complete C code with date validity control.
*/
#include<stdio.h>
void main(){
long d1,m1,y1,d2,m2,y2;
printf("Enter first date day, month, year\n");
scanf("%d%d%d",&d1,&m1,&y1);
printf("Enter second date day, month, year\n");
scanf("%d%d%d",&d2,&m2,&y2);
if((IsValid(d1,m1,y1)==0)||(IsValid(d2,m2,y2)==0)){
printf("Invalid date detected\n");
}else{
d1=DatDif(d1,m1,y1,d2,m2,y2);
printf("\n\n Date difference is %d days\n",d1);
}
}// end main
long DatDif(d1,m1,y1,d2,m2,y2)
{ long suma;
suma=rbdug(d2,m2,y2) - rbdug(d1,m1,y1);
if(y1 != y2){
if(y1 < y2){
suma+=Godn(y1,y2);
}else{
suma-=Godn(y2,y1);
}
}
return(suma);
}// end DatDif
long Godn(yy1,yy2)
{ long jj,bb;
bb=0;
for(jj=yy1;jj<yy2;jj++){
bb+=365;
if(IsLeapG(jj)==1) bb+=1;
}
return(bb);
}// end Godn
//Day of the Year
long rbdug(d,m,y)
{ long a,r[13];
r[1] = 0; r[2] = 31; r[3] = 59; r[4] = 90;
r[5] = 120; r[6] = 151; r[7] = 181; r[8] = 212;
r[9] = 243; r[10]= 273; r[11]= 304; r[12]= 334;
a=r[m]+d;
if((IsLeapG(y)==1)&&(m>2)) a+=1;
return(a);
}//end rbdug
//date validity
long IsValid(dd,mm,yy)
{ long v[13];
if((0 < mm) && (mm < 13)){
v[1] = 32; v[2] = 29; v[3] = 32; v[4] = 31;
v[5] = 32; v[6] = 31; v[7] = 32; v[8] = 32;
v[9] = 31; v[10]= 32; v[11]= 31; v[12]= 32;
if ((mm==2)&&(IsLeapG(yy)==1)) v[2]=30;
if((0 < dd) && (dd < v[mm])){
return(1);
}else{
return(0);
}
}else{
return(0);
}
}//end IsValid
//is leap year in Gregorian
long IsLeapG(yr){
if(((((yr%400)==0)||((yr%100)!=0))&&((yr%4)==0))){
return(1);
}else{
return(0);
}
}//end IsLeapG
Related
I would like the function to return an array of strings where each date is reprsented as "13/11" or any other format from where i can pull both the date and month.
Maybe it would look something like this:
char** get_dates_from_year_and_week(int year, int week) {
//Magic happens
return arr
}
get_dates_from_year_and_week(2021, 45);
//Would return ["08/11", "09/11", 10/11", "11/11", "12/11", "13/11", "14/11"];
How could this possible be obtained using c? Any library is welcome.
To covert the year/week/(day-of-the-week) to a year/month/day, find the date of the first Monday of the year as ISO 8601 week-of-the-year begins on a Monday. Then add week*7 days to that. Use mktime() to determine day-of the-week (since Sunday) and to bring an out-of-range date into its primary range.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct {
int year, month, day;
} ymd;
typedef struct {
int year, week, dow; // ISO week-date: year, week 1-52,53, day-of-the-week 1-7
} ISO_week_date;
int ISO_week_date_to_ymd(ymd *y, const ISO_week_date *x) {
// Set to noon, Jan 4 of the year.
// Jan 4 is always in the 1st week of the year
struct tm tm = {.tm_year = x->year - 1900, .tm_mon = 0, .tm_mday = 4,
.tm_hour = 12};
// Use mktime() to find the day-of-the week
if (mktime(&tm) == -1) {
return -1;
}
// Sunday to Jan 4
int DaysSinceSunday = tm.tm_wday;
// Monday to Jan 4
int DaysSinceMonday = (DaysSinceSunday + (7 - 1)) % 7;
tm.tm_mday += (x->dow - 1) + (x->week - 1) * 7 - DaysSinceMonday;
if (mktime(&tm) == -1) {
return -1;
}
y->year = tm.tm_year + 1900;
y->month = tm.tm_mon + 1;
y->day = tm.tm_mday;
return 0;
}
"array of strings" --> leave that part for OP to do.
I'm new to C-programming and I'm trying to make a code to count the day difference between a date and a birthday.
int year, birth_year;
int year_common;
int year_leap;
for(int i = year; i <= birth_year; i--){
year = i;
if (year % 400 != 0 || (year % 100 == 0 && year % 400 != 0)){
year_common++;
}
if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)){
year_leap++;
}
}
int date_pass = (year_common * 365) + (year_leap * 366);
I wanted the loop to decrement the 'i', add 1 into the year_common integer when it's a common year, and add 1 into the year_leap integer when it's a leap year until it is the same as the birth_year.
For now, I'm still trying to check out the years, but no matter how many year difference I made, they always give out 5856 days.
e.g. :
birth date : 05/11/2005
checked date : 05/11/ 2007
give out '5856 days'
And I don't know where that number comes from.
I tried initializing it with 0, but it gave out 0 days instead.
I tried this code:
int year_pass = year - birth_year;
int year_leap = 0;
for(int i = year; i <= birth_year; i--){
if(i % 400 == 0 || (i % 100 != 0 && i % 4 == 0)){
year_leap++;
}
}
int date_pass = (year_pass * 365) + (year_leap * 1);
And it missed 1 day for the leap year.
Is there something wrong with the loop?
My prof wants the code to be as standard as possible with loops and conditions.
You have declared the year common and year leap as in variables but haven't assigned any value. Since youre adding one unit by ++;, you need to pre define year_leap and year_common =0
int year, birth_year;
int year_common=0;
int year_leap=0;
Dates are hard to handle, with all UTC leap seconds and local timezones - leap years are only the tip of the iceberg. Don't reinvent the wheel. Whenever you want to do something with dates, first thing to do is to convert everything to seconds since epoch. Then you do what you want.
#include <time.h>
#include <stdio.h>
#include <stdint.h>
int main() {
// 05/11/2005
struct tm birthday = {
.tm_year = 2005 - 1900,
.tm_mon = 11,
.tm_mday = 5,
.tm_hour = 12,
};
// 05/11/2007
struct tm end = {
.tm_year = 2007 - 1900,
.tm_mon = 11,
.tm_mday = 5,
.tm_hour = 12,
};
time_t birth_s = mktime(&birthday);
time_t end_s = mktime(&end);
time_t diff_s = end_s - birth_s;
time_t diff_day = diff_s / 3600 / 24;
printf("%ju\n", (uintmax_t)diff_day);
}
I need a function that can calculate the difference between two datetime (year, month, day, hours, minute, seconds). and then return the difference in the same format.
int main (){
struct datetime dt_from;
init_datetime(&dt_from, 1995, 9, 15, 10, 40, 15);
struct datetime dt_to;
init_datetime(&dt_to, 2004, 6, 15, 10, 40, 20);
struct datetime dt_res;
datetime_diff(&dt_from, &dt_to, &dt_res);
return 0;
}
void datetime_diff(struct datetime *dt_from, struct datetime *dt_to
, struct datetime *dt_res) {
//What can I do here to calculate the difference, and get it in the dt_res?
}
Please have a look and try this example which uses time.h and should be portable. It calculates the difference in days between the dates in your question. You can change the program a little so that it works the way you want.
#include <stdio.h>
#include <time.h>
#include <math.h>
int main() {
time_t start_daylight, start_standard, end_daylight, end_standard;;
struct tm start_date = {0};
struct tm end_date = {0};
double diff;
printf("Start date: ");
scanf("%d %d %d", &start_date.tm_mday, &start_date.tm_mon, &start_date.tm_year);
printf("End date: ");
scanf("%d %d %d", &end_date.tm_mday, &end_date.tm_mon, &end_date.tm_year);
/* first with standard time */
start_date.tm_isdst = 0;
end_date.tm_isdst = 0;
start_standard = mktime(&start_date);
end_standard = mktime(&end_date);
diff = difftime(end_standard, start_standard);
printf("%.0f days difference\n", round(diff / (60.0 * 60 * 24)));
/* now with daylight time */
start_date.tm_isdst = 1;
end_date.tm_isdst = 1;
start_daylight = mktime(&start_date);
end_daylight = mktime(&end_date);
diff = difftime(end_daylight, start_daylight);
printf("%.0f days difference\n", round(diff / (60.0 * 60 * 24)));
return 0;
}
Test
Start date: 15 9 1995
End date: 15 6 2004
3195 days difference
Or even simpler for non-interactive code and with standard or daylight savings time:
#include <stdio.h>
#include <time.h>
#include <math.h>
int main()
{
time_t start_daylight, start_standard, end_daylight, end_standard;;
struct tm start_date = {0};
struct tm end_date = {0};
double diff;
start_date.tm_year = 1995;
start_date.tm_mon = 9;
start_date.tm_mday = 15;
start_date.tm_hour = 10;
start_date.tm_min = 40;
start_date.tm_sec = 15;
end_date.tm_mday = 15;
end_date.tm_mon = 6;
end_date.tm_year = 2004;
end_date.tm_hour = 10;
end_date.tm_min = 40;
end_date.tm_sec = 20;
/* first with standard time */
start_date.tm_isdst = 0;
end_date.tm_isdst = 0;
start_standard = mktime(&start_date);
end_standard = mktime(&end_date);
diff = difftime(end_standard, start_standard);
printf("%.0f days difference\n", round(diff / (60.0 * 60 * 24)));
/* now with daylight time */
start_date.tm_isdst = 1;
end_date.tm_isdst = 1;
start_daylight = mktime(&start_date);
end_daylight = mktime(&end_date);
diff = difftime(end_daylight, start_daylight);
printf("%.0f days difference\n", round(diff / (60.0 * 60 * 24)));
return 0;
}
Here is the basic idea:
Convert your datetime into an integral type (preferable long long or unsigned long long) which represents your datetime value as it's smallest unit (second in your case). How to achieve that? Easy transform the single values into seconds and add everything together. (seconds + minutes * 60 + hours * 3600 ...)
Do this for both values and then subtract the integer values.
Now convert the single integer value, the time difference, back to a datetime. How? Start with the biggest unit (years) and divide the difference by the amount of seconds within one year (60 * 60 * 24 * 365). Now you know how many years are in between your two datetimes. Take the rest and divide it by the amount of seconds per month, and so on...
(Obviously I ignored everything rather complicated, like daylight saving time for example)
However I would highly recommend using struct tm from time.h as mentioned in the comments. It is portable and you can use difftime.
I am trying to write a program in C given these two data sets from a user. Year:[Range 1901-2099] and Day in year: [range 1-366] I need a formula to calculate the date in MM/DD/YYYY format. One more thing. No IF/ELSE statements. No AND/OR or GREATER THAN or LESS THAN are allowed.
You can use nested switch case to avoid using if-else.
Find out whether it is a leap year or not.
Create four buckets of months (1-99), (100-199).. etc. Bucket numbers will be used as case numbers.
Now check the left most bit of the day, and write a switch case for assigning it into the right bucket.
Each bucket could be divided into 4 more buckets too (the leap year information will be used).
Repeat step 3 for the middle bit and based on the result (case) switch to appropriate bucket.
Briefly, logic could be as follows:
isLeapYear = year % 4
Switch(isLeapYear)
Case 0: {
first_bucket = days/4
Switch(first_bucket)
{
Case 0: {
days_left = days % 100
second_bucket = days / 50;
// ...
// ...
}
Case 1, 2, 3: {
// Similar logic for non-leap year
// ...
}
You can do it without any kind of flow control statements (if, switch) and without doing leap year calculation yourself. Get the timestamp corresponding to January 1st of the desired year. Then, you can use a single addition on the timestamp to get to the correct day, and convert the timestamp to whatever format you want.
I would provide code, specific function names and explain what you need to add to the timestamp, but since this is obviously a homework question, I won't. If anyone reminds me in two weeks (i.e. when the deadline for the assignment is most likely over) I'll happily post example code.
In case library functions were allowed to be used (which I doubt) I'd do it this (lazy lego) way:
#define _XOPEN_SOURCE /* glibc2 needs this for strptime */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>
int to_date(
char * date,
const size_t size,
const char * fmt,
const short unsigned int day_of_year,
const short unsigned int year)
{
char buffer[16] = "";
sprintf(buffer, "%hu %hu", day_of_year, year);
{
struct tm t = {0};
char * presult = strptime(buffer, "%j %Y", &t);
if ((NULL == presult) || ('\0' != *presult))
{
errno = EINVAL;
return -1;
}
strftime(date, size, fmt, &t);
}
return 0;
}
int main(int argc, char ** argv)
{
if (2 > argc)
{
fprintf(stderr, "Missing arguments. Usage: %s day-of-year year\n", argv[0]);
return EXIT_FAILURE;
}
short unsigned int day_of_year = atoi(argv[1]);
short unsigned int year = atoi(argv[2]);
char date[16] = "";
if (-1 == to_date(date, sizeof(date), "%m/%d/%Y", day_of_year, year))
{
perror("to_date() failed");
return EXIT_FAILURE;
}
printf("Result: day %d of year %d is '%s'.\n", day_of_year, year, date);
return EXIT_SUCCESS;
}
Call it like this
$ ./main 2 2000
to get
Result: day 2 of year 2000 is '01/02/2000'.
For years 1901 to 2099, can easily be done using time functions.
void Makedate(int year, int day, struct tm *dest) {
struct tm tm1 = { 0 };
// Leap year every 4 years, lets do calc referencing 2000-2003
tm1.tm_year = 2000 - 1900 + year % 4;
tm1.tm_mday = day; // Make the Jan 1st to Jan 366th. OK to be out of range.
// Avoid day changes due to DST by using Noon. BTW I doubt this is needed (CYA)
tm1.tm_hour = 12;
// mktime adjusts our fields for us, setting the month, mday, dow, etc.
mktime(&tm1);
tm1.tm_year = year - 1900; // set to selected year
*dest = tm1;
}
int main() {
struct tm tm0;
Makedate(2013, 1, & tm0); printf("y:%4d m:%2d d:%2d\n", tm0.tm_year + 1900, tm0.tm_mon + 1, tm0.tm_mday);
Makedate(2013, 365, & tm0); printf("y:%4d m:%2d d:%2d\n", tm0.tm_year + 1900, tm0.tm_mon + 1, tm0.tm_mday);
Makedate(2020, 1, & tm0); printf("y:%4d m:%2d d:%2d\n", tm0.tm_year + 1900, tm0.tm_mon + 1, tm0.tm_mday);
Makedate(2020, 366, & tm0); printf("y:%4d m:%2d d:%2d\n", tm0.tm_year + 1900, tm0.tm_mon + 1, tm0.tm_mday);
return 0;
}
y:2013 m: 1 d: 1
y:2013 m:12 d:31
y:2020 m: 1 d: 1
y:2020 m:12 d:31
#define TRUE 1
#define FALSE 0
int days_in_month[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
char *months[]=
{
" ",
"\n\n\nJanuary",
"\n\n\nFebruary",
"\n\n\nMarch",
"\n\n\nApril",
"\n\n\nMay",
"\n\n\nJune",
"\n\n\nJuly",
"\n\n\nAugust",
"\n\n\nSeptember",
"\n\n\nOctober",
"\n\n\nNovember",
"\n\n\nDecember"
};
int inputyear(void)
{
int year;
printf("Please enter a year (example: 1999) : ");
scanf("%d", &year);
return year;
}
int determinedaycode(int year)
{
int daycode;
int d1, d2, d3;
d1 = (year - 1.)/ 4.0;
d2 = (year - 1.)/ 100.;
d3 = (year - 1.)/ 400.;
daycode = (year + d1 - d2 + d3) %7;
return daycode;
}
int determineleapyear(int year)
{
if(year% 4 == FALSE && year%100 != FALSE || year%400 == FALSE)
{
days_in_month[2] = 29;
return TRUE;
}
else
{
days_in_month[2] = 28;
return FALSE;
}
}
void calendar(int year, int daycode)
{
int month, day;
for ( month = 1; month <= 12; month++ )
{
printf("%s", months[month]);
printf("\n\nSun Mon Tue Wed Thu Fri Sat\n" );
// Correct the position for the first date
for ( day = 1; day <= 1 + daycode * 5; day++ )
{
printf(" ");
}
// Print all the dates for one month
for ( day = 1; day <= days_in_month[month]; day++ )
{
printf("%2d", day );
// Is day before Sat? Else start next line Sun.
if ( ( day + daycode ) % 7 > 0 )
printf(" " );
else
printf("\n " );
}
// Set position for next month
daycode = ( daycode + days_in_month[month] ) % 7;
}
}
int main(void)
{
int year, daycode, leapyear;
year = inputyear();
daycode = determinedaycode(year);
determineleapyear(year);
calendar(year, daycode);
printf("\n");
}
This code generates a calendar of the inputed year in the terminal.
my question is how can i convert this into a Objective-C syntax instead of this C syntax.
im sure this is simple process but im quite of a novice to objective - c and i need it for a cocoa project. this code outputs the calendar as a continuously series of strings until the last month hits. soo instead of creating the calendar in the terminal how can i input the calendar a series of NSMatrixes depend on the inputed year.
hope somone can help me with this thanks or every helps
(you be in the credits of the finished program) :)
(the calendar is just a small part of the program i making and it is one of the important parts!!)
I would suggest looking at standard NSCalendar class which provides this and many more functions as well.
For example to calculate the number of days in a month (or week) for a given date you can use the following method:
- (NSRange)rangeOfUnit:(NSCalendarUnit)smaller inUnit:(NSCalendarUnit)larger forDate:(NSDate *)date
Some classes that may also be helpful: NSDateComponents and NSDateFormatter.
Note also that c code is completely valid in objective-c so you program should be able to run ok (except you may need to change its input)
Objective-C is a strict superset of C. So you can just use your code, at least the logic part.
Of course you need to convert the input (scanf) and the output (printf) for GUI calls.
That said, don't re-invent the wheel. You can use NSDatePicker, which is a ready-made UI class to show and pick the date. See the documentation.