2

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();
Alina Anjum
  • 1,178
  • 6
  • 30
  • 53
  • 1
    First of all: a year by only three `yyy`? Seconds won't be parsed but are available... Month expected as text but given as numbers. Month 26? Also check the separator. Try [rtm](https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx) – Sebastian Schumann May 12 '16 at 06:43
  • 1
    this can provide you helpful guide http://stackoverflow.com/questions/919244/converting-a-string-to-datetime – Muhammad Faizan Khan May 12 '16 at 06:46
  • I didn't found the solution there.kindly suggest me your answer – Alina Anjum May 12 '16 at 06:50

4 Answers4

2

Life is to easy using 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");
Muhammad Faizan Khan
  • 10,013
  • 18
  • 97
  • 186
1

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"); 
M.S.
  • 4,283
  • 1
  • 19
  • 42
1

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

Dmitry
  • 57
  • 7
  • var passexpiredate = DateTime.Parse("06/26/2016 9:14:03 AM", CultureInfo.InvariantCulture); lblPassExpiry.InnerText = "Password Expiry Date: " + passexpiredate.ToString("dd-MMM-yyy hh:mm tt"); – Dmitry May 12 '16 at 06:55
  • thanks but i got the solution.Support for your answer :) – Alina Anjum May 12 '16 at 06:56
1

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
Nikhil Vartak
  • 5,002
  • 3
  • 26
  • 32