将YYYYMMDDHHMMSS的字符串值格式转换为C#DateTime

时间:2010-06-11 20:14:38

标签: c# datetime

我需要将“YYYYMMDDHHMMSS”形式的字符串值转换为DateTime。但不确定如何,可能会使用DateTime.Tryparse来实现这一点。或者还有其他方法可以做到这一点。我可以使用一些字符串操作来单独使用“YYYYMMDD”,转换为日期时间,然后分别将HH,MM,SS添加到该DateTime。但是,是否有任何DateTime.TryParse()方法可以在一行中将“YYYYMMDDHHMMSS”格式字符串值转换为DateTime值?

3 个答案:

答案 0 :(得分:72)

定义您自己的解析格式字符串以供使用。

string formatString = "yyyyMMddHHmmss";
string sample = "20100611221912";
DateTime dt = DateTime.ParseExact(sample,formatString,null);

如果您的日期时间为毫秒,请使用以下formatString

string format = "yyyyMMddHHmmssfff"
string dateTime = "20140123205803252";
DateTime.ParseExact(dateTime ,format,CultureInfo.InvariantCulture);

由于

答案 1 :(得分:17)

您必须使用custom parsing string。我还建议包括不变文化,以确定这种格式与任何文化无关。另外,它会阻止某些代码分析工具发出警告。

var date = DateTime.ParseExact(value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);

答案 2 :(得分:0)

class Program
{
    static void Main(string[] args)
    {

        int transactionDate = 20201010;
        int? transactionTime = 210000;

        var agreementDate = DateTime.Today;
        var previousDate = agreementDate.AddDays(-1);

        var agreementHour = 22;
        var agreementMinute = 0;
        var agreementSecond = 0;

        var startDate = new DateTime(previousDate.Year, previousDate.Month, previousDate.Day, agreementHour, agreementMinute, agreementSecond);
        var endDate = new DateTime(agreementDate.Year, agreementDate.Month, agreementDate.Day, agreementHour, agreementMinute, agreementSecond);

        DateTime selectedDate = Convert.ToDateTime(transactionDate.ToString().Substring(6, 2) + "/" + transactionDate.ToString().Substring(4, 2) + "/" + transactionDate.ToString().Substring(0, 4) + " " + string.Format("{0:00:00:00}", transactionTime));

        Console.WriteLine("Selected Date : " + selectedDate.ToString());
        Console.WriteLine("Start Date : " + startDate.ToString());
        Console.WriteLine("End Date : " + endDate.ToString());

        if (selectedDate > startDate && selectedDate <= endDate)
            Console.WriteLine("Between two dates..");
        else if (selectedDate <= startDate)
            Console.WriteLine("Less than or equal to the start date!");
        else if (selectedDate > endDate)
            Console.WriteLine("Greater than end date!");
        else
            Console.WriteLine("Out of date ranges!");
    }
}