UPDATE: 也可以封装成一个函数方便调用:
std::string GetTimeString( void )
{
time_t t = time(0);
char timeStr[256];
strftime(timeStr,sizeof(timeStr), "%d/%m/%Y %H:%M:%S",localtime(&t));
string s(timeStr);
return s;
}
==============================================
#include <time.h>
#include <stdio.h>
int main( void )
{
time_t t = time(0);
char tmp[64];
strftime( tmp, sizeof(tmp), "%Y/%m/%d %H:%M:%S %z",localtime(&t) );
puts( tmp );
return 0;
}调用到的函数(仅使用C标准库;能精确到秒级 )size_t strftime(char *strDest, size_t maxsize, const char *format, const struct tm *timeptr); // 取得当地时间,localtime获取的结果由结构tm返回 struct tm *localtime(const time_t *timer);
具体使用的格式信息:
%a 星期几的缩写。Eg:Tue %A 星期几的全名。 Eg: Tuesday %b 月份名称的缩写。 %B 月份名称的全名。 %c 本地端日期时间较佳表示字符串。 %d 用数字表示本月的第几天 (范围为 00 至 31)。日期 %H 用 24 小时制数字表示小时数 (范围为 00 至 23)。 %I 用 12 小时制数字表示小时数 (范围为 01 至 12)。 %j 以数字表示当年度的第几天 (范围为 001 至 366)。 %m 月份的数字 (范围由 1 至 12)。 %M 分钟。 %p 以 ''AM'' 或 ''PM'' 表示本地端时间。 %S 秒数。 %U 数字表示为本年度的第几周,第一个星期由第一个周日开始。 %W 数字表示为本年度的第几周,第一个星期由第一个周一开始。 %w 用数字表示本周的第几天 ( 0 为周日)。 %x 不含时间的日期表示法。 %X 不含日期的时间表示法。 Eg: 15:26:30 %y 二位数字表示年份 (范围由 00 至 99)。 %Y 完整的年份数字表示,即四位数。 Eg:2008 %Z(%z) 时区或名称缩写。Eg:中国标准时间 %% % 字符。
windows下有可以精确到毫秒级的方案
#include <windows.h>
#include <stdio.h>
int main( void )
{
SYSTEMTIME sys;
GetLocalTime( &sys );
printf( "%4d/%02d/%02d %02d:%02d:%02d.%03d 星期%1d\n",sys.wYear,sys.wMonth,sys.wDay,sys.wHour,sys.wMinute, sys.wSecond,sys.wMilliseconds,sys.wDayOfWeek);
return 0;
} 如果只为显示时间到控制台,可以简单完成
1.不仅可以显示,还可以修改
#include<stdlib.h>
#include<iostream>
using namespace std;
void main()
{
system("time");
}2.仅显示用
#include<iostream>
#include<ctime>
using namespace std;
int main()
{
time_t now_time;
now_time = time(0);
cout<<now_time;
return 0;
}
No comments :
Post a Comment