简体   繁体   中英

Set am or pm String to Date Time Format in c#?

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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