Posted By

rtipton on 05/15/09


Tagged

c DateTime


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

umang_nine
vali29
emregulcan
rodrigojuarez


Formatting DateTime


 / Published in: C#
 

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4.  
  5. namespace DateTimeParse
  6. {
  7. class DateConv
  8. {
  9. static void Main(string[] args)
  10. {
  11. // Current Date/Time
  12. Console.WriteLine("Using Now Property --> " + DateTime.Now);
  13. Console.WriteLine("Using Today Property --> " + DateTime.Today);
  14.  
  15. // DateTime in a text format
  16. string datetimeString = "6/2/2006 12:00:00 PM";
  17. Console.WriteLine("Text Formatted Date and Time --> " + datetimeString);
  18.  
  19. // Convert the text DateTime to a DateTime format
  20. // This is just to show the syntax involved in a text to DateTime conversion
  21. DateTime convertedDateTime = DateTime.Parse(datetimeString);
  22. Console.WriteLine("Converted to DateTime --> " + convertedDateTime);
  23.  
  24. // Extract just the date portion of the DateTime variable
  25. string justDate = convertedDateTime.Date.ToShortDateString();
  26. Console.WriteLine("Extract Date Only: --> " + justDate);
  27.  
  28. // Once the variable is in DateTime format - several different variations
  29. Console.WriteLine("d: {0:d}", convertedDateTime);
  30. Console.WriteLine("D: {0:D}", convertedDateTime);
  31. Console.WriteLine("f: {0:f}", convertedDateTime);
  32. Console.WriteLine("F: {0:F}", convertedDateTime);
  33. Console.WriteLine("g: {0:g}", convertedDateTime);
  34. Console.WriteLine("G: {0:G}", convertedDateTime);
  35. Console.WriteLine("m: {0:m}", convertedDateTime);
  36. Console.WriteLine("M: {0:M}", convertedDateTime);
  37. Console.WriteLine("r: {0:r}", convertedDateTime);
  38. Console.WriteLine("R: {0:R}", convertedDateTime);
  39. Console.WriteLine("s: {0:s}", convertedDateTime);
  40. Console.WriteLine("t: {0:t}", convertedDateTime);
  41. Console.WriteLine("T: {0:T}", convertedDateTime);
  42. Console.WriteLine("u: {0:u}", convertedDateTime);
  43. Console.WriteLine("U: {0:U}", convertedDateTime);
  44. Console.WriteLine("y: {0:y}", convertedDateTime);
  45. Console.WriteLine("Y: {0:Y}", convertedDateTime);
  46. }
  47. }
  48. }

Report this snippet  

You need to login to post a comment.