0

I have a DateTime object, I'm getting that DateTime object from some WPF component. Now, that object will be in 12h format. My goal is to transform that object to 24h DateTime object. So, no strings in any directions whatsoever.

Example:

If the user sets on WPF component something like: 01.24.2020 06:00 PM, I need to convert that object to something like:

new DateTime(1, 24, 2020, 18, 00);

Here is my failed attempt:

 private DateTime convertDatesToDBFormat(DateTime start)
    {
        var format = start.ToString("tt", CultureInfo.InvariantCulture);
        int hours = format.Equals("Pm") ? start.Hour + 12 : start.Hour;


        return  new DateTime(start.Year, start.Month, hours, start.Minute, 0, 0);
    }

Also, I'm not really sure what tt means here...

EDIT: Later, when I want to save to database, this is how I'm doing it, when I was using other WPF components (which were giving me desired "form" of DateTime):

 new SqlParameter("@StartDate", Utility.convertDateWithTimeToString(appointment.Period.Start)); //Start property returns DateTime 

 public static string convertDateWithTimeToString(DateTime date)
    {

        return date.ToString("dd-MM-yyyy hh:mm");
    }

And with this, column Start in SQL Server looked like this:

24-01-2020 18:00

But with this new WPF component, I end up in db with this:

24-01-2020 06:00 //even tho I wanted in the evening time 18:00 not 06:00am
Wrapper
  • 794
  • 10
  • 25
  • 3
    A DateTime is in binary format. Always. It only receives a readable format when converted to a string. – John Wu Jan 24 '20 at 18:58
  • 1
    The format you're referring to is only in the way the `DateTime` object is *displayed*. It's not something that's stored in with the object itself. If you're getting a `DateTime` object, then there's nothing more to do. If you're getting a `string` and need to convert it to a `DateTime`, then you need to look at one of the `DateTime.Parse` variants. – Rufus L Jan 24 '20 at 18:59
  • the DateTime Object already does that. Do you want the output as a string in a 24 hour format? – Train Jan 24 '20 at 19:03
  • DateTime itself only stores the Ticks since the start of the Unix Epoch. Everything else - all other properties and even the String Representation - are just a interpretation of that value. The .NET the Parse() and ToString() functions are execptionally good, in that they will go and retrieve the user selected Culture and Format from Windows. You should generally not override that. Only place this somewhat breaks down is with WebServers and Transmitting Data as string. – Christopher Jan 24 '20 at 19:09
  • I edited my question. – Wrapper Jan 24 '20 at 19:18
  • Apparently, I had to say like this: return date.ToString("dd-MM-yyyy HH:mm"); big H instead of small h. Thank you all for useful comments. – Wrapper Jan 24 '20 at 20:00

0 Answers0