开发者

Getting numeric timezone in specified format

I would like to print the current time as 2011-08-18 10:11:12 -07:00. I developed a code snippet a开发者_Go百科s below,

#include <iostream>

using namespace std;

void time_to_string(time_t clock,const char *fmtstr )
{
    char buf[256];
    if (strftime(buf, 256, fmtstr, localtime(&clock)) == 0)
        buf[0] = 0;
    cout << buf << endl;
}

int main()
{
        time_to_string(time(NULL), "%Y-%m-%d %H%M%S %z");
}

I am able to display the time as 2011-08-18 10:11:12 -0700 but not as 2011-08-18 10:11:12 -07:00. Using "%Y-%m-%d %H%M%S %:z" produces 2011-08-18 10:11:12 %:z.

How can i accomplish the above task in C/C++.


You would have to manually split the string which is formated by %z as +hhmm or -hhmm. %z has a fixed format. Look at the description of strftime.

Replaced by the offset from UTC in the ISO 8601:2000 standard format ( +hhmm or -hhmm ), or by no characters if no timezone is determinable.

Build one string with date and time. Build a second string with the offset from UTC with %z, insert the : in the second string. Concatenate first and second string.


It tries to interpret %: and it doesn't match a format specifier, so it prints it out as is. But you probably knew that already =)

In your time_to_string function, I would manually insert the ':' into the buffer before displaying it.


The syntax you tried don't exist.

What I would do is calling the function twice : once with "%Y-%m-%d %H%M%S ", and once with "%z", manually add the : in the second string, and then concatenate the two.

To insert the :, you could do an ugly buffer manipulation :

buf2[5]=buf2[4];
buf2[4]=buf2[3];
buf2[3]=':';

strcat(buf,buf2);

Note that the layout isn't likely to change for this specific data, so it's not so ugly.

0r if you really like overkill, a regexp. But you'll need an external library.


You can manually add the ':' at the end, modifying the result string. e.g.,

buf[26]='\0';
buf[25]=buf[24];
buf[24]=buf[23];
buf[23]=':';

I may be overlooking a better solution.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜