C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#字符串转日期格式

C#实现将字符串转化为日期格式的方法详解

作者:wenchm

这篇文章主要为大家详细介绍了C#如何使用DateTime结构的ParseExact方法和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对象,等效于由format和provider所指定的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.
 */

到此这篇关于C#实现将字符串转化为日期格式的方法详解的文章就介绍到这了,更多相关C#字符串转日期格式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文