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

来源:互联网 发布:淘宝旺铺基础班 编辑:程序博客网 时间:2024/03/29 16:33
 

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

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


#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;
}

0 0
原创粉丝点击