将字符串转换为DateTime

作者:追风剑情 发布于:2016-4-14 14:54 分类:C#

时间字符串与DateTime

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace StringToDateTimeTest
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. Console.WriteLine("当前时间: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss tt 时区z"));
  13.  
  14. //美国: 月份/日期/年份
  15. string date = "01/08/2008";
  16. Console.WriteLine("字符串"+date);
  17. DateTime dt = Convert.ToDateTime(date);
  18. Console.WriteLine("美国 Year: {0}, Month: {1}, Day: {2}", dt.Year, dt.Month, dt.Day);
  19.  
  20. //法国: 日期/月份/年份
  21. IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);//本地化
  22. DateTime dt2 = DateTime.Parse(date, culture, System.Globalization.DateTimeStyles.AssumeLocal);
  23. Console.WriteLine("法国 Year: {0}, Month: {1}, Day {2}", dt2.Year, dt2.Month, dt2.Day);
  24. Console.WriteLine();
  25.  
  26. string dateString = null;
  27.  
  28. Console.WriteLine("字符串null:");
  29. ConvertToDateTime(dateString);
  30.  
  31. Console.WriteLine("字符串empty:");
  32. dateString = String.Empty;
  33. ConvertToDateTime(dateString);
  34.  
  35. Console.WriteLine("字符串not-date:");
  36. dateString = "not a date";
  37. ConvertToDateTime(dateString);
  38.  
  39. // Try to convert various date strings.
  40. Console.WriteLine("------------ 转换不同格式的时间字符串 -----------");
  41. dateString = "05/01/1996";
  42. ConvertToDateTime(dateString);
  43. dateString = "Tue Apr 28, 2009";
  44. ConvertToDateTime(dateString);
  45. dateString = "Wed Apr 28, 2009";
  46. ConvertToDateTime(dateString);
  47. dateString = "06 July 2008 7:32:47 AM";
  48. ConvertToDateTime(dateString);
  49. dateString = "17:32:47.003";
  50. ConvertToDateTime(dateString);
  51. // Convert a string returned by DateTime.ToString("R").
  52. dateString = "Sat, 10 May 2008 14:32:17 GMT";
  53. ConvertToDateTime(dateString);
  54. // Convert a string returned by DateTime.ToString("o").
  55. dateString = "2009-05-01T07:54:59.9843750-04:00";
  56. ConvertToDateTime(dateString);
  57.  
  58.  
  59. Console.Read();
  60. }
  61.  
  62. private static void ConvertToDateTime(string value)
  63. {
  64. DateTime convertedDate;
  65. try
  66. {
  67. convertedDate = Convert.ToDateTime(value);
  68. Console.WriteLine("字符串{0}\n {1}\n Kind: {2}",
  69. value, convertedDate,
  70. convertedDate.Kind.ToString());
  71. }
  72. catch (FormatException)
  73. {
  74. Console.WriteLine("'{0}' is not in the proper format.", value);
  75. }
  76. }
  77. }
  78. }

 

运行结果

111111.png

 

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号