I have
int year=2017;
int month=02;
int day=01;
int hour=11;
int minutes=30;
String format="AM";
DateTime datetime=new DateTime(year,month,day,hour,minutes,0);
So how can i add this AM
or PM
format string
to datetime?
I have
int year=2017;
int month=02;
int day=01;
int hour=11;
int minutes=30;
String format="AM";
DateTime datetime=new DateTime(year,month,day,hour,minutes,0);
So how can i add this AM
or PM
format string
to datetime?
One way is to use a condition:
int year = 2017;
int month = 2;
int day = 1;
int hour = 11;
int minutes = 30;
String format = "AM";
DateTime datetime = new DateTime(year,
month,
day,
(format.ToUpperInvariant() == "PM" && hour < 12) ?
hour + 12 : hour,
minutes,
00);
You can do it in the following way:
dateTime.ToString("yyyy-MM-dd hh:mm tt");
Its the 'tt' that adds the am/pm. Take a look at the MSDN docs (https://msdn.microsoft.com/en-us/library/zdtaw1bw%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396)
The answer is here: Convert to DateTime with AM/PM
DateTime.ParseExact("2/22/2015 9:54:02 AM", "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
In your case:
int year=2017;
int month=02;
int day=01;
int hour=11;
int minutes=30;
String format="AM";
DateTime datetime = DateTime.ParseExact($"{month}/{day}/{year} {hour}:{minutes}:00 {format}",
"M/d/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);