Parsing Integer Value As Datetime

前端 未结 3 645
予麋鹿
予麋鹿 2021-01-17 07:50

I have date represented as integer like 20140820 and I want to parsing it as datetime, like 2014.08.20.

Do I need to parse each integer value (2014)(08)

相关标签:
3条回答
  • 2021-01-17 08:09

    The easiest and most performance way would be something like:

    int date = 20140820;
    
    int d = date % 100;
    int m = (date / 100) % 100;
    int y = date / 10000;
    
    var result = new DateTime(y, m, d);
    
    0 讨论(0)
  • 2021-01-17 08:18

    If your CurrentCulture supports yyyyMMdd format as a standard date and time format, you can just use DateTime.Parse method like;

    int i = 20140820;
    DateTime dt = DateTime.Parse(i.ToString());
    

    If it doesn't support, you need to use DateTime.ParseExact or DateTime.TryParseExact methods to parse it as custom date and time format.

    int i = 20140820;
    DateTime dt;
    if(DateTime.TryParseExact(i.ToString(), "yyyyMMdd", 
                              CultureInfo.InvariantCulture,
                              DateTimeStyles.None, out dt))
    {
        Console.WriteLine(dt);
    }
    

    Then you can format your DateTime with .ToString() method like;

    string formattedDateTime = dt.ToString("yyyy.MM.dd", CultureInfo.InvariantCulture);
    
    0 讨论(0)
  • 2021-01-17 08:20

    Try This :-

    string time = "20140820";
    DateTime theTime= DateTime.ParseExact(time,
                                        "yyyyMMdd",
                                        CultureInfo.InvariantCulture,
                                        DateTimeStyles.None);
    

    OR

    string str = "20140820";
    string[] format = {"yyyyMMdd"};
    DateTime date;
    
    DateTime.TryParseExact(str, 
                              format, 
                              System.Globalization.CultureInfo.InvariantCulture,
                              System.Globalization.DateTimeStyles.None, 
                              out date))
    

    now date variable will have required converted date of string '20140820'

    0 讨论(0)
提交回复
热议问题