简体   繁体   中英

Adding leading zeros to date time C#

What is the best way to add zeros to date time in C#

Example string "9/10/2011 9:20:45 AM" convert to string "09/10/2011 09:20:45 AM"

DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") // 12hour set
DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") // 24hour set

More information / methods about formatting Date can be found Here

From you comment

It's better to use the following to parse a DateTime

DateTime date = DateTime.MinValue;
DateTime.TryParse("9/10/2011 9:20:45 AM", out date);
return date.ToString("MM/dd/yyyy hh:mm:ss tt")

You can then check wether it fails by comparing it to DateTime.MinValue rather then crash the application if the Convert.ToDatetime fails

If you say, that it is both strings, then you should use the DateTime.TryParse method:

DateTime dt;
if (DateTime.TryParse("9/10/2011 9:20:45 AM", out dt))
{
    Console.WriteLine(dt.ToString("dd/MM/yyyy hh:mm:ss tt"));
}
else
{
    Console.WriteLine("Error while parsing the date");
}
myDate.ToString("dd/MM/yyyy hh:mm:ss tt")
DateTime dt = ...
dt.ToString("dd/MM/yyyy hh:mm:ss tt");

你可以使用string.Format("{0:dd/MM/yyyy hh:mm:ss}", dateTime);

使用string stringVariable = string.Format("{0:dd/MM/yyyy hh:mm:ss tt}", dateTimeVariable);

just use this code its will help you..

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms;

namespace DateTimeConvert { public partial class Form1 : Form { public Form1() { InitializeComponent(); }

  private void button1_Click(object sender, EventArgs e) { label1.Text= ConvDate_as_str(textBox1.Text); } public string ConvDate_as_str(string dateFormat) { try { char[] ch = dateFormat.ToCharArray(); string[] sps = dateFormat.Split(' '); string[] spd = sps[0].Split('.'); dateFormat = spd[0] + ":" + spd[1]+" "+sps[1]; DateTime dt = new DateTime(); dt = Convert.ToDateTime(dateFormat); return dt.Hour.ToString("00") + dt.Minute.ToString("00"); } catch (Exception ex) { return "Enter Correct Format like <5.12 pm>"; } } private void button2_Click(object sender, EventArgs e) { label2.Text = ConvDate_as_date(textBox2.Text); } public string ConvDate_as_date(string stringFormat) { try { string hour = stringFormat.Substring(0, 2); string min = stringFormat.Substring(2, 2); DateTime dt = new DateTime(); dt = Convert.ToDateTime(hour+":"+min); return String.Format("{0:t}", dt); ; } catch (Exception ex) { return "Please Enter Correct format like <0559>"; } } } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM