C# Adjust DateTime based on Input Parameter

evci
evci used Ask the Experts™
on
Hi ... need your help with a DateTime issue.  I have a script that runs via a job scheduler. When the 'job' kicks off, it passes the appropriate DateTime (it is not always NOW.  The script runs 24 hours a day at the top of the hour.  Sometimes a job is delayed by 15 minutes to 45 minutes, but will always use the top of the hour time).

The DateTime are passed automatically to my script via @@startDateTime@@ and @@endDateTime@@.  The format of these two parameters are "yyyy-MM-dd 00:00".

Assume
     @@startDateTime@@ = "2016-02-10 10:00"
    @@endDateTime@@ = "2016-02-10 10:59"

I need to return newStartDateTime = "2016-02-10 09:00" and newEndDateTime = "2016-02-10 09:59"
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Are you trying to minus an hour in your C# code?

Author

Commented:
Yes. I need to minus an hour.
Hi,

Here it is.
newStartDateTime = dt.AddHours(-1);
newEndDateTime = dt.AddHours(-1);

Open in new window

Commented:
In other words:
using System;
using System.Globalization;

namespace EE_Q28925390
{
	class Program
	{
		static string start = "2016-02-10 10:00";
		static string end = "2016-02-10 10:59";

		static void Main(string[] args)
		{
			Console.WriteLine("Start @ {0}", JobTime(start));
			Console.WriteLine("End @ {0}", JobTime(end));
			Console.ReadLine();
		}

		static DateTime JobTime(string value)
		{
			var result = default(DateTime);
			DateTime.TryParseExact(value, "yyyy-MM-dd hh:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
			return result.AddHours(-1);
		}
	}
}

Open in new window

Produces the following output -Capture.JPGIf you need to have it formatted, then just use the ToString method with the appropriate format; e.g. -
using System;
using System.Globalization;

namespace EE_Q28925390
{
	class Program
	{
		static string start = "2016-02-10 10:00";
		static string end = "2016-02-10 10:59";

		static void Main(string[] args)
		{
			Console.WriteLine("Start @ {0}", JobTime(start).ToString("yyyy-MM-dd hh:mm"));
			Console.WriteLine("End @ {0}", JobTime(end).ToString("yyyy-MM-dd hh:mm"));
			Console.ReadLine();
		}

		static DateTime JobTime(string value)
		{
			var result = default(DateTime);
			DateTime.TryParseExact(value, "yyyy-MM-dd hh:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
			return result.AddHours(-1);
		}
	}
}

Open in new window

Which now produces the following output -Capture.JPG-saige-

Author

Commented:
Thanks for the help.  Worked.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial