¿Razón de este extraño comportamiento de DateTime?

Tengo este método:

public static DateTime GetDatetime(string ampm, string hour, string minute)
        {
            int iHour = Convert.ToInt32(hour);
            int iMinute = Convert.ToInt32(minute);

            if (ampm == "PM" && iHour != 12)
                iHour = 12 + iHour;

            DateTime dtTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month,
                DateTime.Now.Day, iHour, iMinute, 0);

            return dtTime;
        }

which basically accepts AM/PM and hour and minute and gives DateTime. I give input as

   DateTime startTIme = GetDatetime("AM", "12", "30");

I get time correctly as 12:30 in morning on my local machine. However when I run this same method on server I get 12:30 PM. This is driving me nuts. Can anybody help me out? What am I doing wrong?

Actualizar:

My new function is:

public static DateTime GetDatetime(string ampm, string hour, string minute)
        {
            int iHour = Convert.ToInt32(hour);
            int iMinute = Convert.ToInt32(minute);

            if (ampm == "PM" && iHour != 12)
                iHour = 12 + iHour;
            else if (ampm == "AM" && iHour == 12)
                iHour = 0;

            DateTime dtTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month,
                DateTime.Now.Day, iHour, iMinute, 0);

            return dtTime;
        }

This seem to work fine. Can anybody find any issue in this code?

preguntado el 03 de mayo de 12 a las 14:05

Have you confirmed that both machines are on the same timezone? -

Because 12:30am is actually 00:30. -

Hi Chris, exactly. That is why I updated my code. -

You now have working code and you want us to find issues in it? I think you've just answered your question! :) -

@Dan: I don't believe in myself anymore after what has been happening to me since last 1 hour. So I just asked you guys to see if I have overlooked somthing :p -

4 Respuestas

Your function always returns 12:30 PM (noon) when called with: GetDatetime("AM", "12", "30");

As Eric mentioned the reason you're getting different results might be that the two computers print out dates in a different way.

For example with my settings the result is:

2012-05-03 12:30:00 (half-hour past noon in my computer's format)

With US settings the result is:

5/3/2012 12:30:00 PM (half-hour past noon in US format)

To print the date in the same way on both machines, you can specify a culture info to use for the date formatting:

DateTime dateResult = GetDatetime("AM", "12", "30");
string strResult = dateResult.ToString(System.Globalization.CultureInfo.GetCultureInfo("en-US"));

On all computers strResult will have the following value: 5/3/2012 12:30:00 PM

But most importantly, you should fix your code to get the expected result (12AM should be midnight, not noon).

contestado el 03 de mayo de 12 a las 15:05

So how do I get a consistent date on both machines? Can you please change my code to reflect it? - Jack

Puedes simplemente usar el DateTime.Parse() (enlace msdn) (o TryParse()) method to do this. Look at following example code:

string[] times = new string[] 
{
    "00:00 AM"
    , "01:00 AM"
    , "10:00 AM"
    , "12:00 AM"
    , "00:00 PM"
    , "01:00 PM"
    , "10:00 PM"
    , "12:00 PM"
};

foreach (var time in times)
{
    DateTime date = DateTime.Parse(time);
    Console.WriteLine(date);
}

Da salida:

03/05/2012 00:00:00
03/05/2012 01:00:00
03/05/2012 10:00:00
03/05/2012 00:00:00
03/05/2012 12:00:00
03/05/2012 13:00:00
03/05/2012 22:00:00
03/05/2012 12:00:00

In your case, just make a string that contains "hour":"minutes" + "AM" or "PM". In code that would be (if your input is invalid, the Parse() method throws an exception or else a very weird result)):

public static DateTime GetDatetime(string ampm, string hour, string minute)
{
    return DateTime.Parse(hour + ":" + minute + " " + ampm);
}

contestado el 03 de mayo de 12 a las 17:05

Hi Styxxy, your answer looks promising. +1 for it. However I need to fix up my method. - Jack

Very simple and useful. Thank you! - Jack

Please check the current culture like this:

Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-us");

Because in different cultures, dates are written in different formats. e.g. (may the 3rd) = 3/5/2012 or 5/3/2012 and so on

http://msdn.microsoft.com/en-us/library/system.threading.thread.currentculture.aspx

contestado el 03 de mayo de 12 a las 14:05

That won't affect the code as written - there's no string parsing involved. - dan puzey

@DanPuzey: Culture settings is the reason the OP thinks he's getting different results on the two computers, even though it's not the case. See my answer. - Caballero meta

Your machine isnt setup to use 24 hour clock

The server is.

Change that in the usual way and all will be fine :)

Cómo estilizar tu guardarropa de premamá en el primer, segundo y tercer trimestre

  1. Haga clic en Inicio y luego en Panel de control.
    1. Click Date, Time, Language, and Regional Options, and then click Regional and Language Options.
    2. To change one or more of the individual settings, click Customise.
    3. Got to time tab and the formats are there!

contestado el 03 de mayo de 12 a las 14:05

Hi Chris, I know but my code has nothing to do with any Regional settings. I just want to create a DateTime object with proper hour and minute. That's about it. - Jack

Thats the reason for the different results on your server and your local computer. - Chris

No that's not the reason. The reason is the wrong calculation. See my new function. You'll realize. The results only "seemed" different as Meta-Knight pointed out. It was ("looked") different because of display format. But in reality they were both same. I just need to fix up 1 line. - Jack

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.