如何从convert.datetime()中获得24小时时间结果,当计算一个时间为12小时格式的字符串时



我有一个API,它返回事件日期和事件时间,两者都是字符串值。此外,时间是12小时格式,后面有小写字母am或pm。例如,

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

我正试图将日期和时间保存到数据库中的单个日期时间字段中。

我目前正在使用。。。

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

然后将eventDateTime值保存到SQL Server 2008 R2记录字段中,该字段定义为。。。

[EventDateTime] [datetime] NOT NULL, 

但是,当我在SQL Server中查看结果时,它被存储为24小时,但忽略了正在转换的文本中的am或pm。

例如

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

显示为

2017-02-08 06:09:00.000

代替

2017-02-08 18:09:00.000

我需要做什么才能将日期和时间以24小时格式保存到数据库中,以便我的记录能够正确排序?

这是整个方法。

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;
}
}

在MailPieceExtracts类中,EventDateTime只是一个自动属性。。

public DateTime EventDateTime { get; set; }

提前感谢您提供的任何帮助。

不要使用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.
}

请参阅rextester上的实际示例。

最新更新