C#实现日期格式转换的公共方法类实例
- 作者: 理想家的坏品味
- 来源: 51数据库
- 2022-04-29
本文实例讲述了c#实现日期格式转换的公共方法类。分享给大家供大家参考,具体如下:
这里演示了c#中一些日期格式的转换。
创建公共方法类(utilityhandle.cs),代码如下:
/// <summary> /// 公共方法类 /// </summary> public static class utilityhandle { /// <summary> /// 字符串日期转datetime /// </summary> public static datetime transstrtodatetime(string strdatetime) { datetime now; string[] format = new string[] { "yyyymmddhhmmss", "yyyy-mm-dd hh:mm:ss", "yyyy年mm月dd日 hh时mm分ss秒", "yyyymdhhmmss","yyyy年m月d日 h时mm分ss秒", "yyyy.m.d h:mm:ss", "yyyy.mm.dd hh:mm:ss","yyyy-mm-dd","yyyymmdd" ,"yyyy/mm/dd","yyyy/m/d" }; if (datetime.tryparseexact(strdatetime, format, cultureinfo.invariantculture, datetimestyles.none, out now)) { return now; } return datetime.minvalue; } /// <summary> /// 日期转换 /// </summary> public static string transformdatalong(datetime? datetime) { string result = ""; if (datetime.hasvalue) { result = datetime.value.tostring("yyyy-mm-dd hh:mm:ss"); } return result; } /// <summary> /// 日期转换 /// </summary> public static string transformdatashort(datetime? datetime) { string result = ""; if (datetime.hasvalue) { result = datetime.value.tostring("yyyy-mm-dd"); } return result; } /// <summary> /// 将日期转换成decimal /// </summary> public static decimal transdatetimetodecimal(datetime date) { decimal ret = 0; ret = convert.todecimal(date.tostring("yyyymmddhhmmss")); return ret; } /// <summary> /// 将decimal转换成日期格式 /// </summary> /// <param name="date">yyyymmddhhmmss</param> /// <returns>yyyy-mm-dd hh:mm:ss</returns> public static string transdecimaltodatetime(string date) { datetimeformatinfo dtfi = new cultureinfo("zh-cn", false).datetimeformat; datetime datetime = datetime.now; datetime.tryparseexact(date, "yyyymmddhhmmss", dtfi, datetimestyles.none, out datetime); return datetime.tostring("yyyy-mm-dd hh:mm:ss"); ; } }
ps:这里再为大家推荐几款日期与时间相关工具供大家参考使用:
在日期天数差计算器:
在线日期计算器/相差天数计算器:
在线日期/天数计算器:
在线阴历/阳历转换工具:
在线天数计算器(flash版):
更多关于c#相关内容感兴趣的读者可查看本站专题:《c#字符串操作技巧总结》、《c#数组操作技巧总结》、《c#中xml文件操作技巧汇总》、《c#常见控件用法教程》、《c#程序设计之线程使用技巧总结》、《c#操作excel技巧总结》、《winform控件用法总结》、《c#数据结构与算法教程》及《c#面向对象程序设计入门教程》
希望本文所述对大家c#程序设计有所帮助。
推荐阅读
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
热点文章
团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
0
使用 MSBuild.exe 在发布模式下构建 C# 解决方案
0
当我发布 Web 应用程序时,AfterPublish 脚本不运行
0
构建时 T4 转换的产品仅在下一个构建中使用
0
ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
0
新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
0
如何将条件编译符号(DefineConstants)传递给 msbuild
0
MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
0
NuGet 包还原找不到包,没有源
0
使用 C# 6.0 功能运行 TFS 构建
0