简体   繁体   中英

Convert string to Datetime format dd-MMM-yyyy issue

I am getting the account expiry date of the employee from database in a string variable and the values which is in this string variable is in the format : 6/26/2016 9:14:03 AM. Now i want this format to be converted in dd-mmm-yyyy hh:mm:ss am/pm.How can i resolve this.

I tried the following code :

 DateTime passexpiredate = DateTime.ParseExact(app_user.GetPasswordExpiry(empCode), "dd-MMM-yyy hh:mm tt", null);
  lblPassExpiry.InnerText = "Password Expiry Date: "+passexpiredate.ToString();

使用DateTime.ParseExact使生活变得轻松:

DateTime.ParseExact("12/02/21 10:56:09 AM", "yy/MM/dd HH:mm:ss tt", CultureInfo.InvariantCulture).ToString("dd-MMM-yyyy HH:mm:ss tt");

You've to pass the required date time format in ToString() method as mentioned below:

DateTime passexpiredate = DateTime.Parse(app_user.GetPasswordExpiry(empCode));
lblPassExpiry.InnerText = "Password Expiry Date: " + passexpiredate.ToString("dd-MMM-yyy hh:mm tt"); 

You need to make DateTime from string 6/26/2016 9:14:03 AM. And then format it to dd-mmm-yyyy hh:mm:ss am/pm

DateTime.ParseExact requires you to specify format exactly as it matches with string representation of datetime value. So that's not going to work for your case.

You will have to first convert string to DateTime instance and then format it while displaying.

string date = "6/26/2016 9:14:03 AM";
var dt = DateTime.Parse(date);
var dtStr = dt.ToString("dd-mmm-yyyy hh:mm:ss tt");
Console.WriteLine(dtStr); // Output: 26-14-2016 09:14:03 AM

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