用户登录
用户注册

分享至

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#程序设计有所帮助。

软件
前端设计
程序设计
Java相关