• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

好好小飞机

菜鸟一枚,主要当作笔记和资料收藏,高手请无视
  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

(转)c/c++获取系统时间的函数

一直使用C或C++在Windows上编成,习惯了使用Win API提供的日期时间处理函数,现在由于编写的是接口库,不能够在库里明确的指名使用win32,包含windows.h,一时间对c 和C++提供的日期时间函数还不知道怎么用,网上找了一个,收藏了。以此慰藉七月份懒惰得没写一篇学习技术的博客文章吧.


http://hi.baidu.com/aoran51423/blog/item/0aa2b3dd15592ce576c6388f.html

c++ 获取当前时间

 

 1 #include <iostream>
 2 #include <time.h>
 3 using namespace std;
 4 int main()
 5 {
 6  time_t ltime;
 7  char tmpbuf[128];
 8 
 9 //方法1:分别获取当前时间,日期
10 /* Display operating system-style date and time. */
11   _strtime( tmpbuf );
12   printf( "OS time:\\t\\t\\t\\t%s\\n", tmpbuf ); //打印当前时间
13   _strdate( tmpbuf );
14   printf( "OS date:\\t\\t\\t\\t%s\\n", tmpbuf ); //打印当前日期
15 
16 //方法二:获取当前时间日期
17  time(&ltime); //获取从1970至今经过的秒数
18  cout << ctime(&ltime) << endl; //折算成当前时间日期
19 
20  return 0;
21 }
View Code

 

 

http://hi.baidu.com/wihate/blog/item/d71e0efae184121aa8d3115b.html


//方案— 优点:仅使用C标准库;缺点:只能精确到秒级#include <time.h>

1 #include <stdio.h>
2 int main( void ) 
3 { 
4     time_t t = time(0); 
5     char tmp[64]; 
6     strftime( tmp, sizeof(tmp), "%Y/%m/%d %X %A 本年第%j天 %z",localtime(&t) ); 
7     puts( tmp ); 
8     return 0; 
9 }
View Code

 

size_t strftime(char *strDest, size_t maxsize, const char *format, const struct tm *timeptr);
根据格式字符串生成字符串。struct tm *localtime(const time_t *timer);
取得当地时间,localtime获取的结果由结构tm返回返回的字符串可以依下列的格式而定:恩,说实话下面的这些字符串有时挺有用的,我才出学校的第一份工作,这些是我自己写函数推算的,不知道有这么个现存的东西,悲哀的我
%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 API

1 #include <windows.h> 
2 #include <stdio.h>
3 int main( void ) 
4 { 
5 SYSTEMTIME sys; 
6 GetLocalTime( &sys ); 
7 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); 
8 return 0;
9 }
View Code

 

//方案三,优点:利用系统函数,还能修改系统时间//此文件必须是c++文件#include<stdlib.h>

1 #include<iostream>
2 using namespace std;
3 void main()
4 {
5     system("time");
6 }
View Code

 

//方案四,将当前时间折算为秒级,再通过相应的时间换算即可//此文件必须是c++文件

1 #include<iostream>
2 #include<ctime>
3 using namespace std;int main()
4 {
5 time_t now_time;
6 now_time = time(NULL);
7 cout<<now_time;
8 return 0;
9 }
View Code

 

posted on 2013-09-02 21:41  好好小飞机  阅读(219)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3