如何将“2014-07-23 06:00”字符串转换为“yyyy-MM-dd-HH.mm.ss.ffffff”格式的日期时间

时间:2014-11-10 10:11:27

标签: c# .net

我的值为2014-07-23 06:00的字符串。我需要以yyyy-MM-dd-HH.mm.ss.ffffff格式将此值转换为DateTime。无需转换为需要显示在yyyy-MM-dd-HH.mm.ss.ffffff

中的字符串

但我收到了以下错误。错误 - string was not recognized as a valid datetime

以下是我的代码。任何人都可以帮我解决这个问题。

using System;
using System.Globalization;

public class Example
{
    public static void Main()
    {
        string format = "yyyy-MM-dd-HH.mm.ss.ffffff" ;
        DateTime result;
        const String Date = "2014-07-23 06:00"; ;

        try
        {
            result = DateTime.ParseExact(Date, format,
                CultureInfo.InvariantCulture);
            Console.WriteLine("{0} converts to {1}.", format, result.ToString());
        }
        catch (FormatException)
        {
            Console.WriteLine("{0} is not in the correct format.", format);
        }
    }
}

4 个答案:

答案 0 :(得分:3)

您需要使用其中存在的格式对其进行解析,然后使用目标格式调用ToString。此外,您不希望使用try-catch,尤其是在有TryX方法的情况下:

var input = "2014-07-23 06:00";

var inputFormat = "yyyy-MM-dd HH:mm";    
var outputFormat = "yyyy-MM-dd-HH.mm.ss.ffffff";

DateTime dateTime;
if (DateTime.TryParseExact(
        input, 
        inputFormat, 
        null, 
        System.Globalization.DateTimeStyles.None, 
        out dateTime))
{
    Console.Write(
        "{0} converts to {1}", 
        inputFormat, 
        dateTime.ToString(outputFormat));
}
else
{
    Console.Write("{0} is not the correct format", inputFormat);
}

答案 1 :(得分:0)

试试这个:

string format = "yyyy-MM-dd-HH.mm.ss.ffffff";
            DateTime result;
            const String Date = "2014-07-23 06:00"; ;

            try
            {

                DateTime datDateStarted;
                DateTime.TryParseExact(Date, new string[] { "yyyy-MM-dd HH:ss" }, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out datDateStarted);
                Console.WriteLine(datDateStarted);
            }
            catch (FormatException)
            {
                Console.WriteLine("{0} is not in the correct format.", format);
            }

答案 2 :(得分:0)

VB.NET码:

    Dim format As String = "yyyy-MM-dd-HH.mm.ss.ffffff"
    Dim resultString As String = String.Empty
    Dim inputString As String = "2014-07-23 06:00"

    resultString = DateTime.ParseExact(inputString, "yyyy-MM-dd HH:mm", System.Globalization.CultureInfo.InvariantCulture).ToString(format)

答案 3 :(得分:-2)

this answer我认为你可以使用这行代码:

DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",
                                       System.Globalization.CultureInfo.InvariantCulture)