简体   繁体   English

将字符串转换为Datetime格式dd-MMM-yyyy问题

[英]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. 我正在从数据库中以字符串变量获取雇员的帐户到期日期,并且该字符串变量中的值的格式为: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. 现在我想将此格式转换为dd-mmm-yyyy hh:mm:ss am / pm。如何解决此问题。

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: 您必须在ToString()方法中传递所需的日期时间格式,如下所述:

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. 您需要从字符串6/26/2016 9:14:03 AM设置DateTime。 And then format it to dd-mmm-yyyy hh:mm:ss am/pm 然后将其格式化为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. DateTime.ParseExact要求您完全指定与日期时间值的字符串表示形式匹配的格式。 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. 您将必须首先将字符串转换为DateTime实例,然后在显示时对其进行格式化。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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