c++与c#的时间转换示例分享
时间:2022-08-22 07:21:40
1.C++中的时间:
(1) time_t其实是一个64位的long int类型
(2) time函数:
函数简介:
函数名: time
头文件: time.h
函数原型:time_t time(time_t *timer)
功能: 获取当前的系统时间,返回的结果是一个time_t类型,其实就是一个大整数,其值表示从CUT(Coordinated Universal Time)时间1970年1月1日00:00:00(称为UNIX系统的Epoch时间)到当前时刻的秒数,然后调用localtime将time_t所表示的CUT时间转换为本地时间(我们是+8区,比CUT多8个小时)并转成struct tm类型,分别表该类型的各数据成员示年月日时分秒。
显示系统当前时间:
int main()
{
time_t ltime;
time(<ime);
cout<<ctime(&time);
return 0;
}
ctime函数:
char *ctime(const time_t *timer);
timer:time_t类型指针
返回值:格式为“星期 月 日 小时:分:秒 年\n\0”的字符串
localtime函数:(gmtime函数与之类似)
struct tm *localtime(const time_t *timer);
timer:time_t类型指针
返回值:以tm结构表示的时间指针
asctime函数:
char *asctime(const struct tm *timeptr);
timeptr:结构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类型转换成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类型转换成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));
}
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
spring boot 全局异常处理方法汇总
利用java实现二叉搜索树
![](https://img.aspxhome.com/file/2023/0/61020_0s.png)
java中接口(interface)及使用方法示例
Java多线程编程中使用Condition类操作锁的方法详解
Spring Boot项目如何同时支持HTTP和HTTPS协议的实现
![](https://img.aspxhome.com/file/2023/1/59321_0s.jpg)
Mybatis的详细使用教程
Java反射 Field类的使用全方位解析
LinkedBlockingQueue链式阻塞队列的使用和原理解析
![](https://img.aspxhome.com/file/2023/8/79938_0s.png)
spring cloud gateway如何获取请求的真实地址
![](https://img.aspxhome.com/file/2023/9/60599_0s.png)
使用@PathVariable接收两个参数
Java中的显示锁ReentrantLock使用与原理详解
![](https://img.aspxhome.com/file/2023/4/69694_0s.jpg)
Redis 订阅发布_Jedis实现方法
springboot常用注释的讲解
Unity实现颜色渐变滑动条
![](https://img.aspxhome.com/file/2023/8/83348_0s.gif)
springboot整合websocket最基础入门使用教程详解
![](https://img.aspxhome.com/file/2023/6/78036_0s.png)
Spring4整合Hibernate5详细步骤
java.text.DecimalFormat用法详解
![](https://img.aspxhome.com/file/2023/9/61249_0s.jpg)
SSM框架搭建图文教程(推荐)
![](https://img.aspxhome.com/file/2023/1/59061_0s.png)