string represents date, and reformat it

前端 未结 6 845
情书的邮戳
情书的邮戳 2020-12-21 17:45

The following case: There is a string that has this format \"2012-02-25 07:53:04\"

But in the end, i rather want to end up with this format \"25-02-2012 07:53:04\"

6条回答
  •  眼角桃花
    2020-12-21 18:02

    Others have suggested using Parse - but I'd recommend using TryParseExact or ParseExact, also specifying the invariant culture unless you really want to use the current culture. For example:

    string input = "2012-02-25 07:53:04";
    
    DateTime dateTime;
    if (!DateTime.TryParseExact(input, "yyyy-MM-dd HH:mm:ss",
                                CultureInfo.InvariantCulture,
                                DateTimeStyles.None,
                                out dateTime))
    {
        Console.WriteLine("Couldn't parse value");
    }
    else
    {
        string formatted = dateTime.ToString("dd-MM-yyyy HH:mm:ss",
                                             CultureInfo.InvariantCulture);
        Console.WriteLine("Formatted to: {0}", formatted);
    }
    

    Alternatively using Noda Time:

    string input = "2012-02-25 07:53:04";
    
    // These can be private static readonly fields. They're thread-safe
    var inputPattern = LocalDateTimePattern.CreateWithInvariantInfo("yyyy-MM-dd HH:mm:ss");
    var outputPattern = LocalDateTimePattern.CreateWithInvariantInfo("dd-MM-yy HH:mm:ss");
    
    var parsed = inputPattern.Parse(input);
    if (!parsed.Success)
    {
        Console.WriteLine("Couldn't parse value");
    }
    else
    {
        string formatted = outputPattern.Format(parsed.Value);
        Console.WriteLine("Formatted to: {0}", formatted);
    }
    

提交回复
热议问题