简体   繁体   English

评估时间为12小时格式的字符串时如何从convert.datetime()获取24小时结果

[英]how to get 24 hour time result from convert.datetime() when evaluating a string that has time is 12 hour format

I have an API that returns an event date and event time, both as string values. 我有一个API,它以字符串值形式返回事件日期和事件时间。 In addition, the time is in 12 hour format with a trailing lowercase am or pm. 此外,时间采用12小时制,尾随的小写字母是am或pm。 For example, 例如,

"eventTime": "6:09 pm",
"eventDate": "February 8, 2017", 

And I am trying to save the date and time into a single datetime field in my database. 我正在尝试将日期和时间保存到数据库中的单个datetime字段中。

I am currently using... 我目前正在使用...

DateTime eventDateTime = Convert.ToDateTime($"{a_item.EventDate} {a_item.EventTime}"; 

and then saving the eventDateTime value into a SQL Server 2008 R2 record field that is defined as ... 然后将eventDateTime值保存到定义为...的SQL Server 2008 R2记录字段中

[EventDateTime] [datetime] NOT NULL, 

But when I look at the result in SQL Server, it is stored as if it was 24 hour time but ignoring the am or pm in the text that is being converted. 但是,当我在SQL Server中查看结果时,它的存储时间好像是24小时,但忽略了要转换的文本中的am或pm。

for example, 例如,

"eventTime": "6:09 pm",
"eventDate": "February 8, 2017", 

Shows up as 显示为

2017-02-08 06:09:00.000

Instead of 代替

2017-02-08 18:09:00.000

What do I need to do so that the date and time get saved to the database in 24 hour format so my records will sort properly? 我需要怎么做才能使日期和时间以24小时格式保存到数据库中,以便我的记录可以正确排序?

Here is the whole method. 这是整个方法。

private SaveRecordResult SaveMailPieceExtractRecord(MailEvent a_item, string a_eventSource)
{
    SaveRecordResult result = new SaveRecordResult();
    result.Success = false;
    try
    {
        if (a_item != null && !string.IsNullOrEmpty(a_item.Pic))
        {
            DateTime eventDateTime = DateTime.Now;
            if (!string.IsNullOrEmpty(a_item.EventDate) && !string.IsNullOrEmpty(a_item.EventTime))
            {
                eventDateTime = Convert.ToDateTime($"{a_item.EventDate} {a_item.EventTime}");  
            }

            string scanFacilityName = string.Empty;
            if (!string.IsNullOrEmpty(a_item.EventCity) && !string.IsNullOrEmpty(a_item.EventState))
            {
                scanFacilityName = $"{a_item.EventCity}, {a_item.EventState}";
            }


            MailPieceExtracts mailPieceExtract = new MailPieceExtracts
            {
                Pic = a_item.Pic,
                ExtractFileNumber = a_item.ExtractFileNumber,
                UspsmailerName = a_item.UspsMailerName,
                UspsmailerId = a_item.UspsMailerId,
                DestinationZip = a_item.DestinationZip,
                ScanFacilityZip = a_item.EventZipCode,
                ScanFacilityName = scanFacilityName,
                EventCode = a_item.EventCode,
                EventName = a_item.Event,
                EventDateTime = eventDateTime,
                CountryCode = a_item.EventCountry,
                Recipient = (!String.IsNullOrEmpty(a_item.Name)) ? a_item.Name : a_item.FirmName,
                FileReceivedDate = DateTime.Now,
                CreatedBy = a_eventSource
            };
            m_cdiMainContext.MailPieceExtracts.Add(mailPieceExtract);
            m_cdiMainContext.SaveChanges();
            result.Success = true;
            result.Error = string.Empty;
        }
        return result;
    }
    catch (Exception ex)
    {
        m_logger.LogError(2, ex, "An exception occurred while tryin to save the MailPiece_Extract record for Mail Event : [{@MailEvent}]", a_item);
        string errorMessage = $"Could not save MailPiece_Extracts record for PIC {a_item.Pic} to the database.";
        result.Error = $"{errorMessage}. The error message is [{ex.Message}]";
        return result;
    }

}

In the MailPieceExtracts class, the EventDateTime is just an auto property.. 在MailPieceExtracts类中,EventDateTime只是一个自动属性。

public DateTime EventDateTime { get; set; }

Thanks in advance for any help you can provide. 在此先感谢您提供的任何帮助。

Instead of using Convert.ToDateTime , use DateTime.TryParseExact : 代替使用Convert.ToDateTime ,使用DateTime.TryParseExact

if(DateTime.TryParseExact($"{a_item.EventDate} {a_item.EventTime}", "MMMM d, yyyy h:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out eventDateTime))
{
    // eventDateTime now holds correct datetime, assuming the data transfered was correct. 
}
else
{
    // Failed to parse string as datetime.
}

See live example on rextester. 请参阅关于rextester的实时示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM