Easy String to DateTime, DateTime to String and Formatting


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. // String to DateTime
  2. String MyString;
  3. MyString = "1999-09-01 21:34 PM";
  4. //MyString = "1999-09-01 21:34 p.m."; //Depends on your regional settings
  5.  
  6. DateTime MyDateTime;
  7. MyDateTime = new DateTime();
  8. MyDateTime = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm tt",null);
  9.  
  10.  
  11. //DateTime to String
  12. MyDateTime = new DateTime(1999, 09, 01, 21, 34, 00);
  13. String MyString;
  14. MyString = MyDateTime.ToString("yyyy-MM-dd HH:mm tt");
  15.  
  16. /*
  17. Format String For Dates
  18.  
  19. Your format string is your most important key. In most of my projects, I make it a constant and then refer to the constant value in my code.
  20.  
  21. The following is the most commonly used format characters:
  22.  
  23. d - Numeric day of the month without a leading zero.
  24. dd - Numeric day of the month with a leading zero.
  25. ddd - Abbreviated name of the day of the week.
  26. dddd - Full name of the day of the week.
  27.  
  28. f,ff,fff,ffff,fffff,ffffff,fffffff -
  29. Fraction of a second. The more Fs the higher the precision.
  30.  
  31. h - 12 Hour clock, no leading zero.
  32. hh - 12 Hour clock with leading zero.
  33. H - 24 Hour clock, no leading zero.
  34. HH - 24 Hour clock with leading zero.
  35.  
  36. m - Minutes with no leading zero.
  37. mm - Minutes with leading zero.
  38.  
  39. M - Numeric month with no leading zero.
  40. MM - Numeric month with a leading zero.
  41. MMM - Abbreviated name of month.
  42. MMMM - Full month name.
  43.  
  44. s - Seconds with no leading zero.
  45. ss - Seconds with leading zero.
  46.  
  47. t - AM/PM but only the first letter.
  48. tt - AM/PM ( a.m. / p.m.)
  49.  
  50. y - Year with out century and leading zero.
  51. yy - Year with out century, with leading zero.
  52. yyyy - Year with century.
  53.  
  54. zz - Time zone off set with +/-.
  55. */

URL: http://www.codeproject.com/KB/cs/String2DateTime.aspx?display=Print

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.