您的位置:首页 > 编程语言 > C语言/C++

C语言获取系统本地时间和修改本地时间

2014-01-16 13:12 811 查看
 
网上查了相关系统本地时间,说的有点乱。 获取系统时间修改后,再重新还原回系统时间的时候,常出现时区差。

经测试,关键是把时间保存下来,还原时用。

#include "stdafx.h"

#include<iostream>
 
#include <Windows.h>

using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{

SYSTEMTIME stUTC={0};
  
 

// Get the timezone info.
// TIME_ZONE_INFORMATION TimeZoneInfo;
//GetTimeZoneInformation( &TimeZoneInfo );

// Convert local time to UTC.
//SYSTEMTIME GmtTime = { 0 };
//TzSpecificLocalTimeToSystemTime( &TimeZoneInfo, &T, &GmtTime );
//TzSpecificSystemTimeToLocalTime( &TimeZoneInfo, &T, &GmtTime );

 
  ::GetLocalTime(&stUTC);
    //  memset(&stUTC, 0, sizeof(SYSTEMTIME));

  //time ( &rawtime );
   //timeinfo = localtime ( &rawtime );  

    //获取并保存当前时间,这是关键地方

  //如果是直接通过newstUTC.wHour=oldstUTC.wHour这种方式直接赋值,时间就会出乱。差时区8 小时

WORD d=stUTC.wDay; //获得当前日期

WORD y=stUTC.wYear; //获取当前年份

WORD m=stUTC.wMonth; //获取当前月份

WORD h=stUTC.wHour; //获取当前为几时

WORD mm=stUTC.wMinute; //获取当前分钟

WORD s=stUTC.wSecond; //获取当前秒

//printf ( "\007The   is: %d-%d-%d-%d-%d-%d", y,m,d,h,mm,s );

stUTC.wYear=2013;
stUTC.wMonth=10;
stUTC.wDay=14;

 

stUTC.wHour=h;
stUTC.wMinute=mm;
stUTC.wSecond=s;
 
::SetLocalTime(&stUTC);

cin.get();
memset(&stUTC, 0, sizeof(SYSTEMTIME));
 
//time ( &rawtime );
//timeinfo = localtime ( &rawtime );
 
  ::GetLocalTime(&stUTC);

  h=stUTC.wHour; //获取当前为几时

  mm=stUTC.wMinute; //获取当前分钟

  s=stUTC.wSecond; //获取当前秒

// printf ( "\007The   is: %d-%d-%d-%d-%d-%d", y,m,d,h,mm,s );

stUTC.wYear=y;
stUTC.wMonth=m;
stUTC.wDay=d;

stUTC.wHour=h;
stUTC.wMinute=mm;
stUTC.wSecond=s;
 

::SetLocalTime(&stUTC);

 

   cin.get();

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: