strftime.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Command line utility to output the date under control of a format string
  2. // Copyright 2008 Beman Dawes
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // See http://www.boost.org/LICENSE_1_0.txt
  5. #define _CRT_SECURE_NO_WARNINGS
  6. #include <ctime>
  7. #include <string>
  8. #include <iostream>
  9. #include <cstdlib>
  10. using namespace std;
  11. int main(int argc, char * argv[])
  12. {
  13. if (argc != 2 )
  14. {
  15. cerr <<
  16. "Invoke: strftime format\n"
  17. "Example: strftime \"The date is %Y-%m-%d in ISO format\""
  18. "The format codes are:\n"
  19. " %a Abbreviated weekday name\n"
  20. " %A Full weekday name\n"
  21. " %b Abbreviated month name\n"
  22. " %B Full month name\n"
  23. " %c Date and time representation appropriate for locale\n"
  24. " %d Day of month as decimal number (01 - 31)\n"
  25. " %H Hour in 24-hour format (00 - 23)\n"
  26. " %I Hour in 12-hour format (01 - 12)\n"
  27. " %j Day of year as decimal number (001 - 366)\n"
  28. " %m Month as decimal number (01 - 12)\n"
  29. " %M Minute as decimal number (00 - 59)\n"
  30. " %p Current locale's A.M./P.M. indicator for 12-hour clock\n"
  31. " %S Second as decimal number (00 - 59)\n"
  32. " %U Week of year as decimal number, with Sunday as first day of week (00 - 53)\n"
  33. " %w Weekday as decimal number (0 - 6; Sunday is 0)\n"
  34. " %W Week of year as decimal number, with Monday as first day of week (00 - 53)\n"
  35. " %x Date representation for current locale\n"
  36. " %X Time representation for current locale\n"
  37. " %y Year without century, as decimal number (00 - 99)\n"
  38. " %Y Year with century, as decimal number\n"
  39. " %z, %Z Either the time-zone name or time zone abbreviation, depending on registry settings; no characters if time zone is unknown\n"
  40. " %% Percent sign\n"
  41. ;
  42. return 1;
  43. }
  44. string format = argv[1];
  45. time_t t = time(0);
  46. tm * tod = localtime(&t);
  47. if (!tod)
  48. {
  49. cerr << "error: localtime function failed\n";
  50. return 1;
  51. }
  52. char* s = new char [format.size() + 256];
  53. if (strftime( s, format.size() + 256, format.c_str(), tod ) == 0 )
  54. {
  55. cerr << "error: buffer overflow\n";
  56. return 1;
  57. }
  58. cout << s;
  59. return 0;
  60. }
粤ICP备19079148号