c++與c#的時(shí)間轉(zhuǎn)換示例分享
1.C++中的時(shí)間:
(1) time_t其實(shí)是一個(gè)64位的long int類型
(2) time函數(shù):
函數(shù)簡(jiǎn)介:
函數(shù)名: time
頭文件: time.h
函數(shù)原型:time_t time(time_t *timer)
功能: 獲取當(dāng)前的系統(tǒng)時(shí)間,返回的結(jié)果是一個(gè)time_t類型,其實(shí)就是一個(gè)大整數(shù),其值表示從CUT(Coordinated Universal Time)時(shí)間1970年1月1日00:00:00(稱為UNIX系統(tǒng)的Epoch時(shí)間)到當(dāng)前時(shí)刻的秒數(shù),然后調(diào)用localtime將time_t所表示的CUT時(shí)間轉(zhuǎn)換為本地時(shí)間(我們是+8區(qū),比CUT多8個(gè)小時(shí))并轉(zhuǎn)成struct tm類型,分別表該類型的各數(shù)據(jù)成員示年月日時(shí)分秒。
顯示系統(tǒng)當(dāng)前時(shí)間:
int main()
{
time_t ltime;
time(<ime);
cout<<ctime(&time);
return 0;
}
ctime函數(shù):
char *ctime(const time_t *timer);
timer:time_t類型指針
返回值:格式為“星期 月 日 小時(shí):分:秒 年\n\0”的字符串
localtime函數(shù):(gmtime函數(shù)與之類似)
struct tm *localtime(const time_t *timer);
timer:time_t類型指針
返回值:以tm結(jié)構(gòu)表示的時(shí)間指針
asctime函數(shù):
char *asctime(const struct tm *timeptr);
timeptr:結(jié)構(gòu)tm指針
返回值:格式為“星期 月 日 小時(shí):分:秒 年\n\0”的字符串
例:
#include<stdio.h>
#include <stddef.h>
#include <time.h>
int main(void)
{
time_t timer; //time_t就是long int 類型
struct tm *tblock;
timer = time(NULL);//這一句也可以改成time(&timer);
tblock = localtime(&timer);
printf("Local time is: %s\n",asctime(tblock));
return 0;
}
2.將C++中time_t類型轉(zhuǎn)換成C#中的DateTime類型:
//time_t是世界時(shí)間, 比 本地時(shí)間 少8小時(shí)(即28800秒)
double seconds = 1259666013 + 28800;
double secs = Convert.ToDouble(seconds);
DateTime dt = new DateTime(
1970, 1, 1, 0, 0, 0, DateTimeKind.Unspecified).AddSeconds(secs);
//TimeSpan span =
// TimeSpan.FromTicks(seconds*TimeSpan.TicksPerSecond);
Console.WriteLine(dt);
3.將C#的DateTime類型轉(zhuǎn)換成C++的time_t類型
public static long DateTimeToTime_t(DateTime dateTime)
{
long time_t;
DateTime dt1 = new DateTime(1970, 1, 1,0,0,0);
TimeSpan ts =dateTime - dt1;
time_t = ts.Ticks/10000000-28800;
return time_t;
}
static void Main(string[] args)
{
DateTime dateTime = new DateTime(2009,12,1,19,13,33);
Console.WriteLine(DateTimeToTime_t(dateTime));
}
- C++時(shí)間戳轉(zhuǎn)換成日期時(shí)間的步驟和示例代碼
- C語(yǔ)言中時(shí)間戳轉(zhuǎn)換成時(shí)間字符串的方法
- C語(yǔ)言實(shí)現(xiàn)字符轉(zhuǎn)unix時(shí)間戳的簡(jiǎn)單實(shí)例
- C語(yǔ)言實(shí)現(xiàn)時(shí)間戳轉(zhuǎn)日期的算法(推薦)
- 淺談時(shí)間戳與日期時(shí)間互轉(zhuǎn)C語(yǔ)言
- 在C語(yǔ)言中轉(zhuǎn)換時(shí)間的基本方法介紹
- C++時(shí)間戳轉(zhuǎn)化操作實(shí)例分析【涉及GMT與CST時(shí)區(qū)轉(zhuǎn)化】
相關(guān)文章
C#實(shí)現(xiàn)獲取文件大小并進(jìn)行比較
這篇文章主要為大家詳細(xì)介紹了C#如何實(shí)現(xiàn)獲取文件大小進(jìn)行單位轉(zhuǎn)換與文件大小比較功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2023-03-03C#中的只讀結(jié)構(gòu)體(readonly struct)詳解
這篇文章主要給大家介紹了關(guān)于C#中只讀結(jié)構(gòu)體(readonly struct)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11C#連接SQL Server數(shù)據(jù)庫(kù)的實(shí)例講解
在本篇文章里小編給大家整理了關(guān)于C#連接SQL Server數(shù)據(jù)庫(kù)的實(shí)例內(nèi)容,有需要的朋友們參考學(xué)習(xí)下。2020-01-01