C#---第十九课:时间DateTime相关的应用 Convert.ToDateTime ParseExact TryParseExact

news2024/10/5 15:32:11

文章目录

    • 1.将字符串转换为标准的DateTime格式
    • 2.DateTime数据的相关应用
    • 3.ParseExact的应用
    • 4.TryParseExact的应用


1.将字符串转换为标准的DateTime格式

DateTime 格式是标准的格式,通过这个格式可以方便转换为其他格式、日期的增减、日期的比较等

using System.Diagnostics;

public class DateTime_Deom
{
    public static void Main()
    {
        DateTime dt;
        DateTime dtmin;
        DateTime dtmax;
        dt = Convert.ToDateTime("2015/01/22");
        dtmin = dt.AddDays(-10);
        dtmax = dt.AddMonths(2);
        Console.WriteLine($"{dt}, {dtmin}, {dtmax}");

        Debug.Assert(dtmin>=dt && dt<=dtmax, "Verify Wrong first !");      // 在output窗口输出结果:如果检验错误
        Debug.Assert(dt >= dtmin && dt <= dtmax, "Verify Wrong second !");
        Console.ReadKey();
    }
}


// 2015 / 1 / 22 0:00:00, 2015 / 1 / 12 0:00:00, 2015 / 3 / 22 0:00:00

在这里插入图片描述



2.DateTime数据的相关应用

日期格式:yyyyMMdd HH:mm:ss(注意此字符串的字母大小写很严格)

yyyy:代表年份
MM:  代表月份
dd:  代表天
HH:  代表小时(24小时制)
mm:  代表分钟
ss:  代表秒



DateTime.Now.ToShortTimeString() 
DateTime dt = DateTime.Now; 
dt.ToString();                                  //2005-11-5 13:21:25 
dt.ToFileTime().ToString();                     //127756416859912816 
dt.ToFileTimeUtc().ToString();                  //127756704859912816 
dt.ToLocalTime().ToString();                    //2005-11-5 21:21:25 
dt.ToLongDateString().ToString();               //2005年11月5日 
dt.ToLongTimeString().ToString();               //13:21:25 
dt.ToOADate().ToString();                       //38661.5565508218 
dt.ToShortDateString().ToString();              //2005-11-5 
dt.ToShortTimeString().ToString();              //13:21 
dt.ToUniversalTime().ToString();                //2005-11-5 5:21:25 




dt.Year.ToString();                             //2005 
dt.Date.ToString();                             //2005-11-5 0:00:00 
dt.DayOfWeek.ToString();                        //Saturday 
dt.DayOfYear.ToString();                        //309 
dt.Hour.ToString();                             //13 
dt.Millisecond.ToString();                      //441 
dt.Minute.ToString();                           //30 
dt.Month.ToString();                            //11 
dt.Second.ToString();                           //28 
dt.Ticks.ToString();                            //632667942284412864 
dt.TimeOfDay.ToString();                        //13:30:28.4412864 
dt.ToString();                                  //2005-11-5 13:47:04 



dt.AddYears(1).ToString();                      //2006-11-5 13:47:04 
dt.AddDays(1.1).ToString();                     //2005-11-6 16:11:04 
dt.AddHours(1.1).ToString();                    //2005-11-5 14:53:04 
dt.AddMilliseconds(1.1).ToString();             //2005-11-5 13:47:04 
dt.AddMonths(1).ToString();                     //2005-12-5 13:47:04 
dt.AddSeconds(1.1).ToString();                  //2005-11-5 13:47:05 
dt.AddMinutes(1.1).ToString();                  //2005-11-5 13:48:10 
dt.AddTicks(1000).ToString();                   //2005-11-5 13:47:04 
dt.CompareTo(dt).ToString();                    //0 
dt.Add(?).ToString();                           //问号为一个时间段 
dt.Equals("2005-11-6 16:11:04").ToString();     //False 
dt.Equals(dt).ToString();                       //True 
dt.GetHashCode().ToString();                    //1474088234 
dt.GetType().ToString();                        //System.DateTime 
dt.GetTypeCode().ToString();                    //DateTime


dt.GetDateTimeFormats('s')[0].ToString();       //2005-11-05T14:06:25 
dt.GetDateTimeFormats('t')[0].ToString();       //14:06 
dt.GetDateTimeFormats('y')[0].ToString();       //2005年11月 
dt.GetDateTimeFormats('D')[0].ToString();       //2005年11月5日 
dt.GetDateTimeFormats('D')[1].ToString();       //2005 11 05 
dt.GetDateTimeFormats('D')[2].ToString();       //星期六 2005 11 05 
dt.GetDateTimeFormats('D')[3].ToString();       //星期六 2005年11月5日 
dt.GetDateTimeFormats('M')[0].ToString();       //11月5日 
dt.GetDateTimeFormats('f')[0].ToString();       //2005年11月5日 14:06 
dt.GetDateTimeFormats('g')[0].ToString();       //2005-11-5 14:06 
dt.GetDateTimeFormats('r')[0].ToString();       //Sat, 05 Nov 2005 14:06:25 GMT 



string.Format("{0:d}",dt);                      //2005-11-5 
string.Format("{0}",dt);                        //2005年11月5日 
string.Format("{0:f}",dt);                      //2005年11月5日 14:23 
string.Format("{0:F}",dt);                      //2005年11月5日 14:23:23 
string.Format("{0:g}",dt);                      //2005-11-5 14:23 
string.Format("{0:G}",dt);                      //2005-11-5 14:23:23 
string.Format("{0:M}",dt);                      //11月5日 
string.Format("{0:R}",dt);                      //Sat, 05 Nov 2005 14:23:23 GMT 
string.Format("{0:s}",dt);                      //2005-11-05T14:23:23 
string.Format("{0:t}",dt);                      //14:23 
string.Format("{0:T}",dt);                      //14:23:23 
string.Format("{0:u}",dt);                      //2005-11-05 14:23:23Z 
string.Format("{0:U}",dt);                      //2005年11月5日 6:23:23 
string.Format("{0:Y}",dt);                      //2005年11月 
string.Format("{0}",dt);                        //2005-11-5 14:23:23 
string.Format("{0:yyyyMMddHHmmssffff}",dt); 



# 计算2个日期之间的天数差 
----------------------------------------------- 
DateTime dt1 = Convert.DateTime("2007-8-1"); 
DateTime dt2 = Convert.DateTime("2007-8-15"); 
TimeSpan span = dt2.Subtract(dt1); 
int dayDiff = span.Days + 1; 


# 计算某年某月的天数 
----------------------------------------------- 
int days = DateTime.DaysInMonth(2007, 8); 
days = 31; 



# 给日期增加一天、减少一天 
----------------------------------------------- 
DateTime dt =DateTime.Now; 
dt.AddDays(1); 				//增加一天 
dt.AddDays(-1);				//减少一天 




3.ParseExact的应用


 // Summary:
 //     Converts the specified string representation of a date and time to its System.DateTime
 //     equivalent using the specified format and culture-specific format information.
 //     The format of the string representation must match the specified format exactly.
 //
 // Parameters:
 //   s:
 //     A string that contains a date and time to convert.
 //
 //   format:
 //     A format specifier that defines the required format of s. For more information,
 //     see the Remarks section.
 //
 //   provider:
 //     An object that supplies culture-specific format information about s.
 //
 // Returns:
 //     An object that is equivalent to the date and time contained in s, as specified
 //     by format and provider.

 public static DateTime ParseExact(string s, string format, IFormatProvider? provider);



public class DateTime_Deom
{
    public static void Main()
    {
        string str = "20120626";
        IFormatProvider ifp = new CultureInfo("zh-CN", true);
        DateTime dt = DateTime.ParseExact(str, "yyyyMMdd", ifp);
        Console.WriteLine(dt.ToString("yyyy-M-dd"));
        Console.ReadKey();
    }
}

// 2012-6-26


ParseExact 这种方式解析时间格式,传递的时间字符串与时间format必须一致,否者代码中直接报错如下:

在这里插入图片描述



4.TryParseExact的应用

TryParseExact 避免了代码中直接报错的问题,不错是否能解析成功需要最终判断一下

# TryParseExact Summary

 // Summary:
 //     Converts the specified string representation of a date and time to its System.DateTime
 //     equivalent using the specified format, culture-specific format information, and
 //     style. The format of the string representation must match the specified format
 //     exactly. The method returns a value that indicates whether the conversion succeeded.
 //
 // Parameters:
 //   s:
 //     A string containing a date and time to convert.
 		传递一个时间字符串格式,例如"25/3/2022""2022/3/25"
 //
 //   format:
 //     The required format of s.
 		标准的日期格式"d/M/yyyy"
 //
 //   provider:
 //     An object that supplies culture-specific formatting information about s.
 //
 //   style:
 //     A bitwise combination of one or more enumeration values that indicate the permitted
 //     format of s.
 //
 //   result:
 //     When this method returns, contains the System.DateTime value equivalent to the
 //     date and time contained in s, if the conversion succeeded, or System.DateTime.MinValue
 //     if the conversion failed. The conversion fails if either the s or format parameter
 //     is null, is an empty string, or does not contain a date and time that correspond
 //     to the pattern specified in format. This parameter is passed uninitialized.
 //
 // Returns:
 //     true if s was converted successfully; otherwise, false.

 public static bool TryParseExact(string s, string format, IFormatProvider provider, DateTimeStyles style, out DateTime result)
 {
     DateTimeFormatInfo.ValidateStyles(style, "style");
     return DateTimeParse.TryParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), style, out result);
 }



public class DateTime_Deom
{
    public static void Main()
    {
        DateTime dt;
        bool isValid = DateTime.TryParseExact("25/3/2022", "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal, out dt);
        Console.WriteLine("----->{0}----->{1}", isValid, dt);
        Console.ReadKey();
    }
}


//----->True----->2022 / 3 / 25 0:00:00		// 解析正确的时候,dt正常传入时间格式
//----->False----->0001 / 1 / 1 0:00:00		// 解析错误的时候,dt输出标准时间



本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/125951.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

RK3568平台开发系列讲解(设备驱动篇)等待队列

🚀返回专栏总目录 文章目录 一、等待队列头二、等待队列项三、添加/删除队列四、等待唤醒五、等待事件沉淀、分享、成长,让自己和他人都能有所收获!😄 📢当我们进程去访问设备的时候,经常需要等待有特定事件发生以后再继续往下运行,这个时候就需要在驱动里面实现当条…

以“微”知著,用友ISV生态的力量与担当

由规模化、集约化、智能化带来的影响&#xff0c;不仅可以让养殖户获得更大的养殖密度、更规范的养殖流程、更专业的管理运营&#xff0c;而且能够带动行业发生深远的变革! 养猪也少不了数智化 常言道&#xff1a;民以食为天&#xff0c;猪粮安天下。一头猪就是一个小银行&…

获取微信小程序码传递的参数 / 微信开发者工具模拟扫描小程序码调试

本文主要介绍如何在微信开发者工具中&#xff0c;模拟微信扫描小程序码打开小程序的场景&#xff0c;进行调试。 二维码调试可以看这篇文章&#xff1a;微信开发者工具模拟扫描二维码调试 添加编译模式 添加一个咱们自定义的编译模式 输入模式名称 主要是方便后面的查找 设…

【观察】Oracle NetSuite+德勤中国税务Digital T-Suite:做中国企业“智慧税务”新助手...

伴随着新技术的快速发展&#xff0c;智慧税务成为国家技术力量驱动、治理能力升级背景下的一次全新税务实践。也正因此&#xff0c;继2015年国家税务总局在《“互联网税务”行动计划》中首次提出智慧税务建设目标后&#xff0c;2021年国家再次印发《关于进一步深化税收征管改革…

双非本科到大厂,贫困家庭到深圳买房,我的逆袭之路

20岁的你是否在拼命努力的奋斗呢&#xff1f; 人这一生&#xff0c;其实大大小小有很多的节点&#xff0c;每个年纪该干每个年纪的事情&#xff0c;一步一步的朝前走下去&#xff0c;应该是大部分人目前的现状。 最近一年来&#xff0c;这个号新增了很多的读者&#xff0c;大…

SpringSecurity(二十三)--OAuth2:使用JWT和加密签名(上)对称密钥加密

一、前言 最近阳了所以一直都在休整&#xff0c;大家一定要注意身体&#xff0c;能不阳就不阳&#xff0c;如果阳康后还是一直咳嗽&#xff0c;最好是能去医院看看&#xff0c;这绝对不是专家口中所说的新冠感冒那么简单&#xff0c;也绝对不是什么80%的无症状&#xff0c;大家…

计算机网络——路由信息协议RIP的基本工作原理

&#x1f49f;&#x1f49f;前言 ​ 友友们大家好&#xff0c;我是你们的小王同学&#x1f617;&#x1f617; 今天给大家打来的是 计算机网络——路由信息协议RIP的基本工作原理 希望能给大家带来有用的知识 觉得小王写的不错的话麻烦动动小手 点赞&#x1f44d; 收藏⭐ 评论&…

(四)devops持续集成开发——jenkins的全局工具配置之maven环境安装及配置

前言 本节内容我们主要介绍jenkins中如何集成自定义的maven环境及流水化组件maven插件的安装&#xff0c;这样我们就可以发布流水化的maven项目工程。 正文 上传并安装maven①上传maven安装包 ②解压maven安装包 unzip apache-maven-3.8.3-bin.zip ③配置maven依赖包环境变量…

Attention:何为注意力机制?

本文来自公众号“AI大道理” 人类利用有限的注意力资源从大量信息中快速筛选出高价值信息&#xff0c;这是人类在长期进化中形成的一种生存机制&#xff0c;人类视觉注意力机制极大地提高了视觉信息处理的效率与准确性。 attention从注意力模型的命名方式看&#xff0c;借鉴了…

带你认识不一样的人工智能

人工智能简称AI&#xff0c;它是研究、模拟、延伸和扩展人类智能的理论、方法、技术和应用系统的新兴技术。人工智能是计算机科学的一个领域&#xff0c;正在向机器传递智能&#xff0c;通过模拟人的某些思维过程和智能行为&#xff0c;让机器像人类一样工作、反应和决策。自人…

学习C语言笔记:初始C语言

学习内容&#xff1a; 1.运算符——&#xff1b; 2.函数——main()、printf()&#xff1b; 3.编写一个简单的C程序&#xff1b; 4.创建整型变量&#xff0c;为其赋值并在屏幕上显示其值&#xff1b; 5.换行字符&#xff1b; 6.如何在程序中写注释&#xff0c;创建包含多个函数的…

Docker网络下-自定义网络实战

通过前面两篇的学习,我们对docker网络及四大网络类型都了解了。本文,咱们就来学习docker的自定义网络。我们为什么需要自定义网络呢?是为了让各个主机分门别类,井井有条。方便关联,使得网络之间可以通过服务名进行通信。为什么在容器中,我们要通过服务名进行通信呢?那是…

分享一个门店会员管理系统模板

会员制对于很多人来说都不陌生&#xff0c;进入中国市场几十年的时间里在许多行业都得到了广泛应用。所谓会员制&#xff0c;是指通过向特定的消费群体发放会员卡&#xff0c;并由消费者缴纳会费或者充钱的形式可享受商家的价格折扣、服务等方面优惠的经营形式&#xff0c;从而…

数据库设计以及分布式事务的产生

一、数据库架构的演进 单点时代 1在早期互联网或者当前小型网站,一般数据库和APP都采用单点方式进行部署,系统简单,容易维护读写分离 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29随着互联网的发展,网站访问量越来越大,数据库最先达到瓶颈,…

jenkins环境基本配置

上一篇文章讲解了jenkins的安装&#xff0c;这一篇文章介绍jenkins安装后的基本配置 1.进入jenkins之后&#xff0c;选择右上角admin下拉框选择设置 2.修改密码&#xff0c;并重新登录 3. jenkins的汉化 3.1 Dashboard ➥ Mange Jenkins ➥ Manage Plugins插件管理 ➥ 已安装…

github上有什么好的unity开源项目?

大量项目来袭 一、github上的Unity开源项目 github上的Unity开源项目 项目名称&#xff1a;《TowerDefense》《TowerDefense》 项目链接&#xff1a;《TowerDefense》项目链接 项目简介&#xff1a; 基于 Unity 的塔防示例游戏&#xff0c;此项目主要用来上手和学习基于 Un…

为什么WordPress要禁止编辑主题和插件?如何进行设置呢?

一淘模板问大家为什么WordPress要禁止编辑主题和插件&#xff1f;如何进行设置呢&#xff1f;接下来我们一起了解一下。 首先&#xff0c;为了安全起见&#xff0c;WordPress的安全是非常重要的&#xff0c;禁止编辑主题和插件的许可&#xff0c;即使有人进来&#xff0c;也不…

C# 数据库 类库

一 ADO.NET 1 System.Data名称空间 2 这种访问数据库的技术叫ADO.NET 3 ADO.NET 实现数据库的访问 ①提供标准的CRUD接口&#xff1b; ② 对不同的数据库提供统一的访问接口&#xff1b; 二 ADO.NET技术的发展 1 ODBC&#xff08;Open Database Connection) 2 DAO(Data …

excel文件管理:如何进行密码保护和破解? 上篇

对于一个公司&#xff0c;或者个人来说&#xff0c;有时候我们的数据往往需要加密。比如公司的经营状况和缴纳的税收有关系&#xff0c;人事档案中有每位员工的个人信息和工资组成说明&#xff0c;这些都是不需要无关人员知道的。微软对于EXCEL的设计就比较人性化&#xff0c;考…

如何搭建一套完整的数据指标体系?

如何搭建一套完整的数据指标体系&#xff1f; 你在工作中是不是这样的经常听到这样的对话&#xff1a; 老板&#xff1a;这次宣传活动总共带来了多少流量&#xff1f;你&#xff1a;大概有一万多人吧......老板&#xff1a;这次活动反响怎么样&#xff1f;你&#xff1a;有很多…