目录
一、DateTime.Now.ToString方法
二、实例
一、DateTime.Now.ToString方法
调用DateTime对象的ToString方法可以将当前DateTime对象的值转换为其等效的字符串表示形式,而且ToString方法提供了重载,可以在ToString方法中添加不同的参数,进而将时间转换为各种格式的字符串表示形式。
语法格式如下:
DateTime.Now.ToString("yyyy ");
DateTime.Now.ToString("MM");
DateTime Now.ToString("dd");
DateTime.Now.ToString("HH");
Date Time.Now.ToString("mm");
DateTime.Now.ToString("ss");
参 数 | 描 述 | 参 数 | 描 述 |
yyyy | 年份,范围为0000~9999 | HH | 时,范围为00~23 |
MM | 月份,范围为01~12 | mm | 分钟,范围为00~59 |
dd | 日期,范围为01~31 | ss | 秒,范围为00~59 |
二、实例
// DateTime.Now.ToString()
// 使用指定格式的字符串变量格式化日期字符串
namespace _061
{public partial class Form1 : Form{private GroupBox? groupBox1;private Label? label1;private Button? button1;public Form1(){InitializeComponent();Load += Form1_Load;}private void Form1_Load(object? sender, EventArgs e){// // button1// button1 = new Button{Location = new Point(103, 22),Name = "button1",Size = new Size(75, 23),TabIndex = 0,Text = "开始转化",UseVisualStyleBackColor = true};button1.Click += Button1_Click;// // label1// label1 = new Label{AutoSize = true,ImageAlign = ContentAlignment.TopLeft,Location = new Point(6, 45),Name = "label1",Size = new Size(56, 17),TabIndex = 1,Text = "显示内容"};// // groupBox1// groupBox1 = new GroupBox{Location = new Point(12, 12),Name = "groupBox1",Size = new Size(300, 183),TabIndex = 0,TabStop = false,Text = "日期格式转指定格式"};groupBox1.Controls.Add(label1);groupBox1.Controls.Add(button1);groupBox1.SuspendLayout();// // Form1// AutoScaleDimensions = new SizeF(7F, 17F);AutoScaleMode = AutoScaleMode.Font;ClientSize = new Size(324, 206);Controls.Add(groupBox1);Name = "Form1";StartPosition = FormStartPosition.CenterParent;Text = "将日期格式转化为指定的格式"; groupBox1.ResumeLayout(false);groupBox1.PerformLayout();}/// <summary>/// DateTime.Now.ToString()/// 使用指定格式的字符串变量格式化日期字符串/// </summary>private void Button1_Click(object? sender, EventArgs e){label1!.Text =DateTime.Now.ToString("d") + "\n" +DateTime.Now.ToString("D") + "\n" +DateTime.Now.ToString("f") + "\n" +DateTime.Now.ToString("F") + "\n" +DateTime.Now.ToString("g") + "\n" +DateTime.Now.ToString("G") + "\n" +DateTime.Now.ToString("R") + "\n" +DateTime.Now.ToString("y") + "\n" +"当前系统时间为:" + DateTime.Now.ToString(//使用自定义格式格式化字符串"yyyy年MM月dd日 HH时mm分ss秒");}}
}