1

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?

lwin
  • 3,784
  • 6
  • 25
  • 46
  • Did you search something? – kgzdev Jan 31 '17 at 08:32
  • 2
    Possible duplicate of [how to convert a string containing AM/PM to DateTime?](http://stackoverflow.com/questions/28672191/how-to-convert-a-string-containing-am-pm-to-datetime) – Mong Zhu Jan 31 '17 at 08:35
  • Yep, They say to change from string.format() to date time.I just want to known can i add this format when i create new date time. – lwin Jan 31 '17 at 08:36

3 Answers3

2

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);
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
1

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)

  • 2
    I guess the op wants to have the reversed process. Constructing the `DateTime` from this information that you are printing with `ToString` – Mong Zhu Jan 31 '17 at 08:38
1

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);
Community
  • 1
  • 1
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76