Subtracting Times with Date

I thought this might have been a simple task...I need to subtract 4 hours from the current datetime that is input.  The datetime format is mm/dd/yyyy hh:mm and the hours are a 24 hour clock.  After it's input, I then take and parse this string into a strDate array and strTime array by doing args[0].split('/') and args[1].split(':').  After this is where I try to subtract the 4 hours, but there's a whole lot to account for as in if the hour is 1, you'd have to go to the previous day and if the day is the first day of the month, going back one day would take you back another month, etc. 

Is there an easier way to do this   The month is really what's throwing me.  Thanks in advance for the help!



Answer this question

Subtracting Times with Date

  • Radioedit420

    in the System.Globalization namespace :-)

  • Dave Auld

    Where is CultureInfo Error (26): The type or namespace name 'CultureInfo' could not be found (are you missing a using directive or an assembly reference )

  • Ljhopkins

    i dont know if this will help
    try the code below..

    good luck!

    private void Form1_Load(object sender, System.EventArgs e)
    {
    DateTime x;
    x = DateTime.Now;
    x.AddHours(-4);
    this.Text = x.ToString();
    }


  • seprice

    James had a very good point. Your code scares me. Always when parsing string to DateTime the method ParseExact should be used. If you test a litle you will find the solution and have one line of code instead of 10, and will work independently from current Windows account datetime settings.

  • Caesar Samsi - MSFT

    You needn't go through all that work:


    string time = args[0] + ' ' + args[1];

    DateTime toDateTimeStamp =
    DateTime.ParseExact(time, "MM/dd/yyyy HH:mm",
    CultureInfo.CurrentCulture);

    DateTime fromDateTimeStamp = toDateTimeStamp .AddHours(-4);



  • Martinp23

    hehe, makes sense...

    Code still didn't work after compiling but it works with my original code. Thanks for the help!


  • J_Dude2003

    Perfection. I just make two DateTime stamps exactly the same and run the DateTime.AddHours(-4) and it works perfectly. Thanks Vincent!

    //Command Line sent: mm/dd/yyyy hh:mm (24 hour format on time)

    string[] strDate = args[0].Split('/');

    string[] strTime = args[1].Split(':');

    System.DateTime toDateTimeStamp = new DateTime(Convert.ToInt16(strDate[2]),Convert.ToInt16(strDate[0]), +

    Convert.ToInt16(strDate[1]),Convert.ToInt16(strTime[0]),Convert.ToInt16(strTime[1]),0);

    System.DateTime fromDateTimeStamp = new DateTime(Convert.ToInt16(strDate[2]),Convert.ToInt16(strDate[0]), +

    Convert.ToInt16(strDate[1]),Convert.ToInt16(strTime[0]),Convert.ToInt16(strTime[1]),0);

    fromDateTimeStamp = fromDateTimeStamp.AddHours(-4);


  • Ron L

    Yes, I did end up changing this. Thanks!
  • Subtracting Times with Date