I'm getting data from a third-party API. I'm receiving a date string like this "04/28/2021 04:25p"
. Can't convert this string into a DateTime value.
I've tried the following:
var dateValue = DateTime.ParseExact(
"04/28/2021 04:25p",
"MM/dd/yyyy HH:mm tt",
new CultureInfo("en-US"));
What is it I'm missing here?
Update: I've used double quotes in my code, forgot to put double-quote here. Updated the question now.
CodePudding user response:
You can use a single letter AM/PM-designator, but then it has to be uppercase:
var dateValue = DateTime.ParseExact(
"04/28/2021 04:25p".ToUpper(),
"MM/dd/yyyy hh:mmt",
new CultureInfo("en-US"));
Otherwise you need to add the 'm':
var dateValue = DateTime.ParseExact(
"04/28/2021 04:25p" "m",
"MM/dd/yyyy hh:mmtt",
new CultureInfo("en-US"));
The third option is to code your own CultureInfo, where DateTimeFormat.AMDesignator is 'm' and DateTimeFormat.PMDesignator is 'p':
public class SingleLetterDesignatorCultureInfo : CultureInfo
{
private DateTimeFormatInfo dateTimeFormatInfo;
public SingleLetterDesignatorCultureInfo():base(CultureInfo.InvariantCulture.Name)
{
dateTimeFormatInfo = base.DateTimeFormat;
dateTimeFormatInfo.PMDesignator = "p";
dateTimeFormatInfo.AMDesignator = "a";
}
public override DateTimeFormatInfo DateTimeFormat
{
get => dateTimeFormatInfo;
set => base.DateTimeFormat = value;
}
}
var dateValue = DateTime.ParseExact(
"04/28/2021 04:25p",
"MM/dd/yyyy hh:mmtt",
new SingleLetterDesignatorCultureInfo());
CodePudding user response:
Firstly, use double-quotes. Secondly, you can stick an "m" at the end of the input to help with the formatting.
string inputPlusM = "04/28/2021 04:25p" "m";
var dt = DateTime.ParseExact(inputPlusM, "MM/dd/yyyy hh:mmtt", new System.Globalization.CultureInfo("en-US") );