C#使用DateTime结构的ParseExact方法和Parse方法分别将字符串转化为日期格式

目录

一、涉及到的知识点 

1.ParseExact(String, String, IFormatProvider)

2.DateTime.ToLongDateString 方法

3.Parse(String)方法

二、实例1:ParseExact方法

1.源码

2.生成效果 

3.示例2

三、实例2:Parse方法


        在程序设计过程中,经常需要显示系统日期,使用DateTime结构的Now属性可以获取系统的日期信息,此时调用ToString方法,将会返回日期的字符串表示,那么,怎样将字符串转换为日期格式呢?ParseExact方法可以轻松地实现此功能。

一、涉及到的知识点 

1.ParseExact(String, String, IFormatProvider)

       将日期和时间的指定字符串表示形式转换为其等效的 DateTime。 字符串表示形式的格式必须与指定的格式完全匹配,否则会引发异常。

publie static DateTime ParseExact(string s,string format,IFormatProvider provider)

参数
s    String
包含要转换的日期和时间的字符串。

format    String
用于定义所需的 s 格式的格式说明符。 有关详细信息,请参阅“备注”部分。

provider    IFormatProvider
一个对象,提供有关 s 的区域性特定格式信息。

返回
DateTime
一个对象,它等效于 s 中包含的日期和时间,由 format 和 provider 指定。

例外
ArgumentNullException
s 或 format 为 null。

FormatException
s 或 format 是一个空字符串。
或 -
s 不包含与 format 中指定的模式相对应的日期和时间。
或 -
s 中的小时组件和 AM/PM 指示符不一致。

        ParseExact方法中的参数说明如下表:

    

   

   s

字符串对象,表示包含要转换的日期和时间的字符串

format

字符串对象,表示s的预期格式

provide

实现IFormatProvider接口的对象,表示用于提供有关s的区域性特定格式信息的IFormatProvider

DateTime

方法返回DateTime对象,等效于由formatprovider所指定的s中包含的日期和时间

2.DateTime.ToLongDateString 方法

        将当前 DateTime 对象的值转换为其等效的长日期字符串表示形式。

public string ToLongDateString ();

返回
String
一个字符串,它包含当前 DateTime 对象的长日期字符串表示形式。
// DateTime.ToLongDateString 方法
using System.Globalization;

namespace _067_3
{
    class Sample
    {
        public static void Main()
        {
            // 初始化 DateTime 对象
            Console.WriteLine("Initialize the DateTime object to Jan 28, 2024 22:23:15 PM.\n");
            DateTime datetime = new(2024, 1, 28, 22, 23, 15);

            // 当前区域
            Console.WriteLine($"Current culture: \"{CultureInfo.CurrentCulture.Name}\"\n");
            var dtFormat = CultureInfo.CurrentCulture.DateTimeFormat;

            // Display the long date pattern and string.
            Console.WriteLine($"Long date pattern: \"{dtFormat.LongDatePattern}\"");
            Console.WriteLine($"Long date string:  \"{datetime.ToLongDateString()}\"\n");

            // Display the long time pattern and string.
            Console.WriteLine($"Long time pattern: \"{dtFormat.LongTimePattern}\"");
            Console.WriteLine($"Long time string:  \"{datetime.ToLongTimeString()}\"\n");

            // Display the short date pattern and string.
            Console.WriteLine($"Short date pattern: \"{dtFormat.ShortDatePattern}\"");
            Console.WriteLine($"Short date string:  \"{datetime.ToShortDateString()}\"\n");

            // Display the short time pattern and string.
            Console.WriteLine($"Short time pattern: \"{dtFormat.ShortTimePattern}\"");
            Console.WriteLine($"Short time string:  \"{datetime.ToShortTimeString()}\"\n");
        }
    }
}
// 运行结果:
/*
Initialize the DateTime object to Jan 28, 2024 22:23:15 PM.

Current culture: "zh-CN"

Long date pattern: "yyyy-MM-dd"
Long date string:  "2024-01-28"

Long time pattern: "HH:mm:ss"
Long time string:  "22:23:15"

Short date pattern: "yyyy-MM-dd"
Short date string:  "2024-01-28"

Short time pattern: "H:mm"
Short time string:  "22:23"


 */

3.Parse(String)方法

        使用当前区域性的约定将日期和时间的字符串表示形式转换为其 DateTime 等效的表示形式。

public static DateTime Parse (string s);

参数
s    String
包含要转换的日期和时间的字符串。 有关详细信息,请参阅要分析的字符串。

返回
DateTime
一个对象,它等效于 s 中包含的日期和时间。

例外
ArgumentNullException
s 为 null。

FormatException
s 不包含日期和时间的有效字符串表示形式。

二、实例1:ParseExact方法

1.源码

// 使用ParseExact方法将字符串转化为日期格式
namespace _067
{
    public partial class Form1 : Form
    {
        private GroupBox? groupBox1;
        private Button? button1;
        private Label? label3;
        private Label? label2;
        private Label? label1;
        private TextBox? textBox3;
        private TextBox? textBox2;
        private TextBox? textBox1;

        public Form1()
        {
            InitializeComponent();
            Load += Form1_Load;
        }
        private void Form1_Load(object? sender, EventArgs e)
        {
            // 
            // label3
            // 
            label3 = new Label
            {
                AutoSize = true,
                Location = new Point(285, 37),
                Name = "label3",
                Size = new Size(20, 17),
                TabIndex = 5,
                Text = "日"
            };
            // 
            // label2
            //         
            label2 = new Label
            {
                AutoSize = true,
                Location = new Point(203, 37),
                Name = "label2",
                Size = new Size(20, 17),
                TabIndex = 4,
                Text = "月"
            };
            // 
            // textBox2
            //          
            textBox2 = new TextBox
            {
                Location = new Point(147, 31),
                Name = "textBox2",
                Size = new Size(50, 23),
                TabIndex = 1
            };
            // 
            // textBox1
            //           
            textBox1 = new TextBox
            {
                Location = new Point(35, 31),
                Name = "textBox1",
                Size = new Size(80, 23),
                TabIndex = 0
            };
            // 
            // label1
            //  
            label1 = new Label
            {
                AutoSize = true,
                Location = new Point(121, 37),
                Name = "label1",
                Size = new Size(20, 17),
                TabIndex = 3,
                Text = "年"
            };
            // 
            // textBox3
            //          
            textBox3 = new TextBox
            {
                Location = new Point(229, 31),
                Name = "textBox3",
                Size = new Size(50, 23),
                TabIndex = 2
            };
            // 
            // button1
            //           
            button1 = new Button
            {
                Location = new Point(141, 81),
                Name = "button1",
                Size = new Size(75, 23),
                TabIndex = 0,
                Text = "转为日期",
                UseVisualStyleBackColor = true
            };
            button1.Click += Button1_Click;
            // 
            // groupBox1
            // 
            groupBox1 = new GroupBox
            {
                Location = new Point(12, 12),
                Name = "groupBox1",
                Size = new Size(340, 63),
                TabIndex = 0,
                TabStop = false,
                Text = "输入日期字符串"
            };
            groupBox1.Controls.Add(label3);
            groupBox1.Controls.Add(label2);
            groupBox1.Controls.Add(textBox2);
            groupBox1.Controls.Add(textBox1);
            groupBox1.Controls.Add(label1);
            groupBox1.Controls.Add(textBox3);
            groupBox1.SuspendLayout();

            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(364, 116);
            Controls.Add(button1);
            Controls.Add(groupBox1);
            Name = "Form1";
            StartPosition = FormStartPosition.CenterScreen;
            Text = "用ParseExact方法将字符串转为日期";
            groupBox1.ResumeLayout(false);
            groupBox1.PerformLayout();
        }
        /// <summary>
        /// 得到日期字符串
        /// 将字符串转换为日期格式
        /// </summary>
        private void Button1_Click(object? sender, EventArgs e)
        {
            string str = string.Format("{0}/{1}/{2}",textBox1!.Text, textBox2!.Text, textBox3!.Text);
            DateTime datetime = DateTime.ParseExact(str, "yyyy/MM/dd", null); 
            MessageBox.Show("输入的日期为: "+ datetime.ToLongDateString(), "提示!");
        }
    }
}

2.生成效果 

 

3.示例2

// ParseExact 方法
using System.Globalization;

namespace _067_1
{
    public class Example
    {
        public static void Main()
        {
            string dateString, format;
            DateTime result;
            CultureInfo provider = CultureInfo.InvariantCulture;

            // 解析不变区域的日期值
            dateString = "01/28/2024";
            format = "d";
            try
            {
                result = DateTime.ParseExact(dateString, format, provider);
                Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
            }
            catch (FormatException)
            {
                Console.WriteLine("{0} is not in the correct format.", dateString);
            }

            // 使用“d”格式解析月份中不带前导零的日期值
            // 不变区域的标准短日期模式需要两位数的月份
            // 否则抛出 FormatException
            dateString = "1/28/2024";
            try
            {
                result = DateTime.ParseExact(dateString, format, provider);
                Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
            }
            catch (FormatException)
            {
                Console.WriteLine("{0} is not in the correct format.", dateString);
            }

            // 使用自定义说明符转换日期和时间。
            dateString = "Sun 28 Jan 2024 8:30 AM -06:00";
            format = "ddd dd MMM yyyy h:mm tt zzz";
            try
            {
                result = DateTime.ParseExact(dateString, format, provider);
                Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
            }
            catch (FormatException)
            {
                Console.WriteLine("{0} is not in the correct format.", dateString);
            }

            // 转换带偏移量的日期和时间,但没有分钟的偏移量时,
            // “zzz”说明符需要以小时为单位前导零,
            // 否则抛出 FormatException
            // 这里有两处错误:1日不是Sun和06:00
            dateString = "Sun 01 Jan 2024 8:30 AM -06";
            try
            {
                result = DateTime.ParseExact(dateString, format, provider);
                Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
            }
            catch (FormatException)
            {
                Console.WriteLine("{0} is not in the correct format.", dateString);
            }

            dateString = "28/01/2024 08:45";
            format = "g";
            provider = new CultureInfo("fr-FR");
            try
            {
                result = DateTime.ParseExact(dateString, format, provider);
                Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
            }
            catch (FormatException)
            {
                Console.WriteLine("{0} is not in the correct format.", dateString);
            }

            // 使用法语(法国)和不变区域转换包含秒和毫秒的日期
            dateString = "28/01/2024 08:30:15.006542";
            format = "dd/MM/yyyy HH:mm:ss.ffffff";
            try
            {
                result = DateTime.ParseExact(dateString, format, provider);
                Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
            }
            catch (FormatException)
            {
                Console.WriteLine("{0} is not in the correct format.", dateString);
            }
        }
    }
}
// 运行结果:
/*
01/28/2024 converts to 2024-01-28 00:00:00.
1/28/2024 is not in the correct format.
Sun 28 Jan 2024 8:30 AM -06:00 converts to 2024-01-28 22:30:00.
Sun 01 Jan 2024 8:30 AM -06 is not in the correct format.
28/01/2024 08:45 converts to 2024-01-28 08:45:00.
28/01/2024 08:30:15.006542 converts to 2024-01-28 08:30:15.

 */

三、实例2:Parse方法

// 以Parse(String)方法转换多个日期和时间值的字符串表示形式
using System.Globalization;

namespace _067_2
{
    public class DateTimeParser
    {
        public static void Main()
        {
            DateTime dateValue;
            string datetime = "1/28/2024 12:15:12 PM";
            try
            {
                dateValue = DateTime.Parse(datetime);
                Console.WriteLine("'{0}' converted to {1}.", datetime, dateValue);
            }
            catch (FormatException)
            {
                Console.WriteLine("Unable to convert '{0}'.", datetime);
            }

            // Reverse month and day to conform to the fr-FR culture.
            // The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
            datetime = "28/01/2024 12:35:20";   //正确顺序01/28/2024
            try
            {
                dateValue = DateTime.Parse(datetime);
                Console.WriteLine("'{0}' converted to {1}.", datetime, dateValue);
            }
            catch (FormatException)
            {
                Console.WriteLine("Unable to convert '{0}'.", datetime);
            }

            // formatted according to conventions of zh-HK Chinese - Hong Kong SAR culture.
            // 没有zh-CN Chinese - China和zh-CHS Chinese (Simplified) , Neutral
            try
            {
                dateValue = DateTime.Parse(datetime, new CultureInfo("zh-HK", false));
                Console.WriteLine("'{0}' converted to {1}.", datetime, dateValue);
            }
            catch (FormatException)
            {
                Console.WriteLine("Unable to convert '{0}'.", datetime);
            }

            // 转换字符串型日期,不包含时间
            datetime = "1/28/2024";
            try
            {
                dateValue = DateTime.Parse(datetime);
                Console.WriteLine("'{0}' converted to {1}.", datetime, dateValue);
            }
            catch (FormatException)
            {
                Console.WriteLine("Unable to convert '{0}'.", datetime);
            }
        }
    }
}
//运行结果:
/*
'1/28/2024 12:15:12 PM' converted to 2024-01-28 12:15:12.
Unable to convert '28/01/2024 12:35:20'.
'28/01/2024 12:35:20' converted to 2024-01-28 12:35:20.
'1/28/2024' converted to 2024-01-28 00:00:00.

 */

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

有趣的css - 好看的呼吸灯效果

整体效果 这个效果主要用 css3 的 animation 属性来实现的。 这个效果可以用作在网站的整体 Loading&#xff0c;也可以放在网站首屏当一个 banner 的背景也是非常棒的&#xff01; 代码部分 html 部分代码&#xff1a; <div class"app"><span class&quo…

4. MySQL 多表查询

重点&#xff1a; MySQL 的 三种安装方式&#xff1a;包安装&#xff0c;二进制安装&#xff0c;源码编译安装。 MySQL 的 基本使用 MySQL 多实例 DDLcreate alter drop DML insert update delete DQL select 3.5&#xff09;DDL 语句 表&#xff1a;二维关系 设计表&…

SAR图像目标识别的可解释性问题探讨

源自&#xff1a;雷达学报 作者&#xff1a;郭炜炜, 张增辉, 郁文贤&#xff0c;孙效华 “人工智能技术与咨询” 发布 摘 要 合成孔径雷达(SAR)图像目标识别是实现微波视觉的关键技术之一。尽管深度学习技术已被成功应用于解决SAR图像目标识别问题&#xff0c;并显著超越了…

扫描电子显微镜电子束辐射损伤和如何减轻

扫描电镜&#xff08;Scanning Electron Microscope, SEM&#xff09;是一种常用的材料表征技术&#xff0c;它通过聚焦电子束扫描样品表面&#xff0c;利用电子与样品相互作用产生的信号来获得高分辨率的形貌图像。然而&#xff0c;电子束的辐射可能会对样品造成损伤&#xff…

初探 Backstage:快速上手指南

坦白说&#xff0c;虽然我之前阅读过相关文档&#xff0c;但实际上从未亲自尝试运行 Backstage。我一直有种感觉&#xff0c;Backstage 不过是一个开发者门户而非开发者平台。上周在 分享我对平台工程的理解 后&#xff0c;朋友圈中有人提议我写一篇关于 Backstage 入门的文章。…

(M)unity受伤反弹以及死亡动画

受伤反弹 1.在人物控制脚本中添加受伤后速度将为0&#xff0c;并添加一个反弹的力 在刷新移动时&#xff0c;需要在没有受伤的状态 public bool isHurt; public float hurtForce; private void FixedUpdate() {if(!isHurt)Move(); }public void GetHurt(Transform attacker) …

11.1 StringBuffer类(血干JAVA系列)

StringBuffer类 11.1.1 认识 StringBuffer 类1.实例操作1——字符串连接操作(append)【例11.1】通过append()方法连接各种类型的数据【例11.2】验证StringBuffer的内容是可以修改的 2.实例操作2——在任意位置处为StringBuffer添加内容&#xff08;insert&#xff09;【例11.3】…

Mac本上快速搭建redis服务指南

文章目录 前言1. 查看可用版本2.安装指定版本的redis3.添加redis到PATH3.1 按照执行brew install命令后输出的提示信息执行如下命令将redis添加到PATH3.2 执行命令要添加的redis环境信息生效: 4. 增加密码4.1 在文件中找到requirepass所在位置4.2 去掉注释并将requirepass值替换…

微信小程序开发如何实现阴影/悬浮效果

显示&#xff1a; 实现&#xff1a; <view style"width: 100%;height: 500rpx; display: flex; justify-content:space-evenly;align-items: center; "><view style"width: 200rpx;height:100rpx;background-color: aqua; display: flex; align-item…

使用antdesign3.0、echarts制作固定资产后台管理系统原型

学了半个月Axure,周末用半天时间&#xff0c;照着网上的模板做了一个固定资产后台管理系统的原型。重点是内联框架的使用&#xff0c;和对echarts表格js代码的调试。原型链接&#xff1a;https://qoz5rv.axshare.com 资产管理系统

SpringBoot 3.1.7集成 Redis 6.2.13及Redis哨兵模式安装

一、背景 我们在开发互联网项目时&#xff0c;常常需要需要用到分布式缓存&#xff0c;目前最流行的分布式缓存就是Redis了&#xff0c;没有之一&#xff0c;接下来&#xff0c;开始我们的Redis实战之旅吧 二、安装单机Redis 1 版本选择 打开Redis官网&#xff0c;找一个版…

JVM篇----第十三篇

系列文章目录 文章目录 系列文章目录前言一、Parallel Old 收集器(多线程标记整理算法)二、CMS 收集器(多线程标记清除算法)三、G1 收集器前言 前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站,这篇文章男女通用,看…

四川古力未来科技公司抖音小店选品攻略从零到一

随着抖音的日益火爆&#xff0c;抖音小店也应运而生&#xff0c;成为了电商行业的新宠儿。但对于许多新手商家来说&#xff0c;如何从众多的商品中挑选出适合自己店铺的商品&#xff0c;却是一件非常头疼的事情。本文将为你揭秘抖音小店的选品攻略&#xff0c;让你轻松玩转电商…

免费分享一套微信小程序外卖跑腿点餐(订餐)系统(uni-app+SpringBoot后端+Vue管理端技术实现) ,帅呆了~~

大家好&#xff0c;我是java1234_小锋老师&#xff0c;看到一个不错的微信小程序外卖跑腿点餐(订餐)系统(uni-appSpringBoot后端Vue管理端技术实现) &#xff0c;分享下哈。 项目视频演示 【免费】微信小程序外卖跑腿点餐(订餐)系统(uni-appSpringBoot后端Vue管理端技术实现)…

好友管理系统----Python实例练习

题目描述 如今的社交软件层出不穷&#xff0c;虽然功能千变万化&#xff0c;但都具有好友管理系统的基本功能&#xff0c;包括添加好友&#xff0c;删除好友&#xff0c;备注好友&#xff0c;展示好友等。次案例要求用Python中的列表知识实现。 程序代码 print("欢迎使…

js引入jqury实现数字滚动效果

页面展示 需要滚动的数字 加个类名 eg:counter <div class"desc_item"><div class"desc_top"><span class"counter">20</span>年</div><div class"desc_btm">20年软件开发经验</div></d…

无心剑中译蒂斯黛尔《任它被遗忘》

Let It Be Forgotten 任它被遗忘 Sarah Teasdale 莎拉蒂斯黛尔 Let it be forgotten, as a flower is forgotten, Forgotten as a fire that once was singing gold, Let it be forgotten forever and ever, Time is a kind friend, he will make us old. 任它被遗忘&…

LeetCode(2)

目录 概念解释 栈 队列 树 树的概念 结点的分类 有序树 无序树 森林 二叉树 满二叉树 完全二叉树 二叉排序树 平衡二叉树 1.用栈实现队列 解法&#xff1a;双栈 2.字符串解码 解法&#xff1a;栈 3.二叉树的中序遍历 解法一&#xff1a;递归 解法二&#xff…

数据结构(一)------顺序表

文章目录 前言一、什么是顺序表二、实现顺序表1.静态顺序表2.动态顺序表总结 前言 制作不易&#xff01;三连支持一下呗&#xff01;&#xff01;&#xff01; 从今天起我们将会进入数据结构的学习&#xff01; 我们先来了解 什么是数据结构 数据结构是计算机存储、组织数…

喜报|「云原生数据库PolarDB」、「阿里云瑶池一站式数据管理平台」揽获“2023技术卓越奖”

日前&#xff0c;国内知名IT垂直媒体&技术社区IT168公布2023年“技术卓越奖”评选结果&#xff0c;经由行业CIO/CTO大咖、技术专家及IT媒体三方的联合严格评审&#xff0c;阿里云瑶池数据库揽获两项大奖&#xff1a;云原生数据库PolarDB荣获“2023年度技术卓越奖”&#xf…