C#中比较常用的DateTime结构的使用方法

2019-12-30 10:57:54王振洲

二、ToString方法

 DateTime的ToString方法有四种重载方式。其中一个重载方式允许传入String,这就意味着你可以将当前DateTime对象转换成等效的字符串形式。比如我们将当前时间输出,日期按yyyy-mm-dd格式,时间按hh:mm:ss格式。
 

  1. Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd"));    Console.WriteLine(DateTime.Now.ToString("hh:mm:ss")); 
?

还有一个重载形式是需要提供IFormatProvider,使用指定的区域性特定格式信息将当前 DateTime 对象的值转换为它的等效字符串表示形式。
 

  1. static void Main(string[] args)      { 
  2.       CultureInfo jaJP = new CultureInfo("ja-JP");        jaJP.DateTimeFormat.Calendar = new JapaneseCalendar(); 
  3.       DateTime date1 = new DateTime(1867, 1, 1);        DateTime date2 = new DateTime(1967, 1, 1); 
  4.               try 
  5.       {          Console.WriteLine(date2.ToString(jaJP)); 
  6.         Console.WriteLine(date1.ToString(jaJP));        } 
  7.       catch (ArgumentOutOfRangeException)        { 
  8.         Console.WriteLine("{0:d} is earlier than {1:d} or later than {2:d}",                   date1, 
  9.                  jaJP.DateTimeFormat.Calendar.MinSupportedDateTime,                   jaJP.DateTimeFormat.Calendar.MaxSupportedDateTime); 
  10.       }        Console.ReadLine(); 
  11.     }