c++與c#的時間轉(zhuǎn)換示例分享
1.C++中的時間:
(1) time_t其實是一個64位的long int類型
(2) time函數(shù):
函數(shù)簡介:
函數(shù)名: time
頭文件: time.h
函數(shù)原型:time_t time(time_t *timer)
功能: 獲取當(dāng)前的系統(tǒng)時間,返回的結(jié)果是一個time_t類型,其實就是一個大整數(shù),其值表示從CUT(Coordinated Universal Time)時間1970年1月1日00:00:00(稱為UNIX系統(tǒng)的Epoch時間)到當(dāng)前時刻的秒數(shù),然后調(diào)用localtime將time_t所表示的CUT時間轉(zhuǎn)換為本地時間(我們是+8區(qū),比CUT多8個小時)并轉(zhuǎn)成struct tm類型,分別表該類型的各數(shù)據(jù)成員示年月日時分秒。
顯示系統(tǒng)當(dāng)前時間:
int main()
{
time_t ltime;
time(<ime);
cout<<ctime(&time);
return 0;
}
ctime函數(shù):
char *ctime(const time_t *timer);
timer:time_t類型指針
返回值:格式為“星期 月 日 小時:分:秒 年\n\0”的字符串
localtime函數(shù):(gmtime函數(shù)與之類似)
struct tm *localtime(const time_t *timer);
timer:time_t類型指針
返回值:以tm結(jié)構(gòu)表示的時間指針
asctime函數(shù):
char *asctime(const struct tm *timeptr);
timeptr:結(jié)構(gòu)tm指針
返回值:格式為“星期 月 日 小時:分:秒 年\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是世界時間, 比 本地時間 少8小時(即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));
}
相關(guān)文章
WPF利用CommunityToolkit.Mvvm實現(xiàn)級聯(lián)選擇器
這篇文章主要介紹了WPF如何利用CommunityToolkit.Mvvm實現(xiàn)級聯(lián)選擇器,文中的示例代碼講解詳細(xì),對我們的學(xué)習(xí)或工作有一定幫助,需要的小伙伴可以參考一下2023-12-12
automation服務(wù)器不能創(chuàng)建對象 解決方法
本文主要介紹如何解決“automation服務(wù)器不能創(chuàng)建對象”錯誤,從而解決Visual Studio.Net不能正常使用的問題,需要的朋友可以參考下。2016-06-06
C#創(chuàng)建數(shù)據(jù)庫及附加數(shù)據(jù)庫的操作方法
這篇文章主要介紹了C#創(chuàng)建數(shù)據(jù)庫及附加數(shù)據(jù)庫的操作方法,涉及C#針對數(shù)據(jù)庫常見的創(chuàng)建、添加、連接等操作技巧,需要的朋友可以參考下2016-06-06
使用C# 調(diào)用deepseek api接口實現(xiàn)正常訪問的過程
本文介紹了使用C#調(diào)用deepseek API接口實現(xiàn)正常訪問的方法,包括解決SSL/TLS安全通道問題和切換模型等常見問題,并提供了默認(rèn)使用的reasoner模型和賬戶余額信息,感興趣的朋友一起看看吧2025-02-02
C#使用HttpClient對大文件進(jìn)行斷點上傳和下載
這篇文章主要介紹了C#如何使用HttpClient對大文件進(jìn)行斷點上傳和下載,文章通過代碼示例講解的非常詳細(xì),具有一定的參考價值,需要的朋友可以參考下2024-06-06
詳解如何利用C#實現(xiàn)設(shè)置系統(tǒng)時間
這篇文章主要為大家詳細(xì)介紹了如何利用C#實現(xiàn)設(shè)置系統(tǒng)時間功能,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)C#有一定的幫助,感興趣的小伙伴可以跟隨小編一起了解一下2022-12-12
C#?wpf?通過HwndHost渲染視頻的實現(xiàn)方法
日常開發(fā)中,特別是音視頻開發(fā),需要在界面上渲染視頻,比如制作一個播放器、或者視頻編輯工具、以及視頻會議客戶端。通常拿到的是像素格式數(shù)據(jù),此時需要渲染到wpf窗口上就需要一定的方法,本文介紹一種通過hwnd渲染的方法,控件既能提供hwnd又能嵌入wpf窗口里2021-11-11

