在编程中经常要用到将日期变量转换为字符串的情况,而且不同的时候希望
转换成不同格式的字符串
下面是一些常用的转换及转换结果:
private void Form1_Load(object sender, System.EventArgs e)
{
textBox1.Text=DateTime.Now.ToString("d");
textBox2.Text=DateTime.Now.ToString("D");
textBox3.Text=DateTime.Now.ToString("G");
textBox6.Text=DateTime.Now.ToString("g");
textBox5.Text=DateTime.Now.ToString("T");
textBox4.Text=DateTime.Now.ToString("t");
textBox12.Text=DateTime.Now.ToString("F");
textBox11.Text=DateTime.Now.ToString("f");
textBox10.Text=DateTime.Now.ToString("M");
textBox9.Text=DateTime.Now.ToString("R");
textBox8.Text=DateTime.Now.ToString("s");
textBox7.Text=DateTime.Now.ToString("u");
textBox13.Text=DateTime.Now.ToString("Y");
textBox14.Text=DateTime.Now.ToString("y");
}
效果比对:
下面是另外的方法转换的结果:
private void Form2_Load(object sender, System.EventArgs e)
{
textBox1.Text=DateTime.Now.ToString("M/d/yyyy");
textBox2.Text=DateTime.Now.ToString("MM/dd/yy");
textBox3.Text=DateTime.Now.ToString("d-MMMM-yy");
textBox6.Text=DateTime.Now.ToString("ddMMyyyy");
textBox5.Text=DateTime.Now.ToString("dd日MM月yyyy年");
textBox4.Text=DateTime.Now.ToString("yyyy年MM月dd日");
textBox12.Text=DateTime.Now.ToString("yyyy年");
textBox11.Text=DateTime.Now.ToString("MM月");
textBox10.Text=DateTime.Now.ToString("dd日");
textBox9.Text=DateTime.Now.ToString("hh:mm:ss");
textBox8.Text=DateTime.Now.ToString("M/d/yyyy H:mm");
textBox7.Text=DateTime.Now.ToString("H:mm:ss");
}
效果比对: