开发者

get first day of given week

开发者 https://www.devze.com 2023-01-22 12:36 出处:网络
I have the current week as an integer (43 as of now). I need the date for Monday in a format like \'Mon Oct 25\'.

I have the current week as an integer (43 as of now). I need the date for Monday in a format like 'Mon Oct 25'.

Thought I could accomplish that by a function from but I don't know how to do that. Any suggestions?

EDIT: I tried the suggestion from R., but it doesn't开发者_如何转开发 give the expected result. Did I implement it wrong?

time_t monday;
char date_format[32];
time_t now = time(NULL);
struct tm *tm = localtime(&now);

tm->tm_yday = 0; // reset to Jan 1st
tm->tm_hour = 24 * 7 * WEEK + 24; // goto Sun and add 24h for Mon

monday = mktime(tm);

strftime(date_format, 31, "%a : %D", tm);

printf("%s\n", date_format);


Note: Not tested, but given the current year, this should do it:

const char *months[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep",
                        "Oct","Nov","dec","Jan"};
/* Start with January 1st of the current year */
struct tm curYear={
  0, // secs
  0, // mins
  0, // hours
  1, // Day of month
  0, // Month (Jan)
  year,
  0, // wday
  0, // yday
  0}; // isdst

/* Offset the number of weeks specified */
time_t secsSinceEpoch=mktime(&curYear)+
                      weekNum*86400*7; /* Shift by number of weeks */
struct tm *candidateDate=gmtime(&secsSinceEpoch);

/* If the candidate date is not a Monday, shift it so that it is */
if (candidateDate->tm_wday!=1)
{
  secsSinceEpoch+=(86400*(candidateDate->tm_wday-1)); 
  candidateDate=gmtime(&secsSinceEpoch);
}

printf("Mon %s %d",months[candidateDate->tm_mon],candidateDate->tm_mday\n");

You may have to adjust the formulas in this code depending on what exactly you mean by week 43 of a given year or to conform with ISO-8601, for example. However, this should present you with good boiler plate code to get started. You may also want to parameterize the day of the week, so that it is not hard coded.

Also, if you want, you can avoid the months array and having to format the time, by truncating the result of the ctime function, which just so happens to display more than you asked for. You would pass to it a pointer to the secsSinceEpoch value and truncate its output to just display the day of the week, the day of the month and the abbreviation of the months name.


The mktime function can do this. Simply initialize struct tm foo to represent the first day of the year (or first day of the first week of the year, as needed), then set tm_hour to 24*7*weeknum and call mktime. It will normalize the date for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消