String to time format but how? - c#

I want to change a value from int or string format to datetime format. There is any function in SQL like the following?:
Function: Result
TimeAdd( nextrundate,"sec",45) 00:00:45
TimeAdd( nextrundate,"min",45) 00:45:00
TimeAdd( nextrundate,"hour",4) 04:00:00
But:
TimeAdd( nextrundate,"min",70) 01:10:00
TimeAdd( nextrundate,"min",190) 03:10:00
Is there a method that does this in C# also?

You mean:
TimeSpan.FromSeconds(double)
TimeSpan.FromMinutes(double)
see MSDN: http://msdn.microsoft.com/en-us/library/system.timespan_members(VS.80).aspx

System.TimeSpan s = new TimeSpan();
s.Add(new TimeSpan(days, hours, minutes, seconds, milliseconds))

In SQL you could use something like
convert(varchar(8),dateadd(second,45,nextrundate),114)
convert(varchar(8),dateadd(minute,45,nextrundate),114)
convert(varchar(8),dateadd(hour,4,nextrundate),114)

In C# you can use the DateTime and TimeSpan classes.
DateTime rundate = DateTime.Now();
DateTime nextRunDate= rundate .AddDays(1);
TimeSpan oneDay=(TimeSpan)(nextRunDate-rundate);
There are similar methods for minutes, seconds etc.

DateTime d = new DateTime();
d = d.AddMinutes(70);
Console.WriteLine(d.ToString("yyyy-MM-dd HH:mm:ss"));

DateTime d = new DateTime();
d = d.AddMinutes(70);
Console.WriteLine(d.ToString("yyyy-MM-dd HH:mm:ss"));

Related

How to get a DateTime from total amount of seconds?

Let's say I have
int seconds = 43200;
(amount of seconds from the beginning of the current day, 00:00:00) and I want to get related DateTime representation ("12:00:00"). Is there any c# utility function?
You need the TimeSpan, then you can get the DateTime in this way:
TimeSpan timeOfDay = TimeSpan.FromSeconds( seconds );
DateTime dt = DateTime.Today.Add( timeOfDay );
It is not a DateTime representation, it looks like a TimeSpan representation to me instead.
For this, you can use TimeSpan.FromSeconds method like;
int seconds = 43200;
var ts = TimeSpan.FromSeconds(seconds);
If you really need to add this to generate current day midday, you can use DateTime.Today property and add this to that.
DateTime dt = DateTime.Today.Add(ts);
You can calculate it directly:
int seconds = 43200;
DateTime dateTime = DateTime.Today.AddSeconds(seconds);

How can I setup DateTime hour,minute and second?

private void StartAuction()
{
DateTime closeDate;
closeDate = DateTime.Parse(Console.ReadLine());
}
I am able to set the date,month and year but I want the hours,minutes and seconds to setup automatically to the current time of the day. for example if the current time is 15:24, I want the user to add the date which could be 21/03/2013 and then I want the time to be 15:24:00 and not 00:00:00 as it currently does.
Any suggestions?
Well you can use DateTime.Now to get the current time, then take the TimeOfDay from that and add it to the Date of your existing DateTime:
private void StartAuction()
{
DateTime closeDate = DateTime.Parse(Console.ReadLine());
DateTime closeDateAtCurrentTime = closeDate.Date + DateTime.Now.TimeOfDay;
...
}
(I'm explicitly using the Date property so that even if the user does enter a time as well, it's basically stripped.)
As a blatant plug, you might also want to consider using my Noda Time library, which separates out the ideas of "date", "time" and "date/time" into different types. (As well as "local" values vs ones where you know the UTC offset or the time zone.)
var now = DateTime.Now;
var date = new DateTime(input.Year, input.Month, input.Day, now.Hour, now.Minute, now.Second);
First you need to parse with DateTime.Parse what you read from command line.
Then, you can do that using DateTime.Now.TimeOfDay like;
DateTime closeDate = DateTime.Parse(Console.ReadLine());
closeDate = closeDate.Date + DateTime.Now.TimeOfDay;
You could do
closeDate = DateTime.Parse(Console.ReadLine() + " " + DateTime.Now.TimeOfDay);
Which works, but does look a little roundabout and I wouldn't recommend it considering you're converting from a time format to a string and then back to a time format again. Lots of immutable objects being created, there.
There are other options, including to parse the date, as you do, and then add TimeOfDay to it.
DateTime closeDate;
closeDate = DateTime.Parse(Console.ReadLine());
closeDate = closeDate.Date + Date.Now.TimeOfDay;
You can do this:
closeDate = DateTime.Parse(Console.ReadLine())
.Add(DateTime.Now - DateTime.Today);
Well how about this little function:
public static DateTime ChangeTime(DateTime dateTime)
{
return new DateTime(
dateTime.Year,
dateTime.Month,
dateTime.Day,
DateTime.Now.Hour,
DateTime.Now.Minute,
DateTime.Now.Second,
DateTime.Now.Millisecond,
DateTime.Now.Kind);
}
This is a possible solution:
store DateTime.Now in a variable
var date = DateTime.Now;
Then u can access the Hours, Minutes and Seconds like this:
date.Hour;
date.Minute;
date.Second;

How do I subtract one DateTime from another?

I have an instance of DateTime that I get from my database, I want to subtract it from DateTime.Now and find out if 4 hours were passed. How do I do that?
Also when should i use DateTime.UTCNow or DateTimeOffset
You can use the subtraction operator to get a TimeSpan:
private static readonly TimeSpan MinimumTime = TimeSpan.FromHours(4);
...
if ((dateFromDatabase - DateTime.Now) > MinimumTime)
{
...
}
As for whether you need UTCNow or Now... it will depend on what happens to time zones when you fetch the data from the database. DateTime is not terribly clear on this front :(
If you can fetch the value as a DateTimeOffset to start with, then you can use DateTimeOffset.Now instead and it should be simpler to work out any time zone issues.
DateTime.Subtract
First Google hit..
Try this:
bool fourHoursPassed = date.AddHours(4) < DateTime.Now;
or this to actually perform a subtraction:
bool fourHoursPassed = (DateTime.Now - date).TotalHours > 4;
DateTime.Subtract
or
DateTime myDateTime = someValue;
TimeSpan ts = DateTime.Now -myDateTime;
if(ts.Hours>=4)
{
doSomething();
}
Hope it helps.
DateTime dt = new DateTime(2011, 07, 10);
DateTime dob = new DateTime(1987, 07, 10);
You can simply subtract as:
TimeSpan age = dt - dob;

Adding days to a DateTime in C#

Is it possible to add dates in C#?
(DateTime.Today.ToLongDateString() + 10)
I tried this but it doesn't work.
Do you want to add days?
DateTime newDate = DateTime.Today.AddDays(10);
Note that you get a new DateTime back!
MSDN
Use DateTime.Today.AddDays(10) or any of the other AddXXX functions on DateTime.
What is the unit of 10. If it is days; then
var todayPlus10Days = DateTime.Today.AddDays(10);
Use AddDays() method:
DateTime dt = DateTime.Today;
dt = dt.AddDays(10);

Add or Sum of hours like 13:30+00:00:20=13:30:20 but how?

I want to add seconds (00:00:02) or minutes (00:00:20) on datetime value (may be stored string type) but how? Examples:
13:30+02:02:02= 15:32:02 ,
13:30+00:00:01= 13:30:01 ,
13:30+00:01:00=13:31:00 or 13:30 (not important)
Can you help me? I need your cool algorithm :) Thanks again...
myDateTimeVariable.Add(new TimeSpan(2,2,2));
If you choose to use the TimeSpan, be aware about the Days part:
TimeSpan t1 = TimeSpan.Parse("23:30");
TimeSpan t2 = TimeSpan.Parse("00:40:00");
TimeSpan t3 = t1.Add(t2);
Console.WriteLine(t3); // 1.00:10:00
With DateTime:
DateTime d1 = DateTime.Parse("23:30");
DateTime d2 = DateTime.Parse("00:40:00");
DateTime d3 = d1.Add(d2.TimeOfDay);
Console.WriteLine(d3.TimeOfDay); // 00:10:00
Adding two datetimes from strings:
var result = DateTime.Parse(firstDate) + DateTime.Parse(secondDate);
Adding a string time to a datetime:
var result = existingDateTime.Add(TimeSpan.Parse(stringTime);
Adding time as in your example:
var result = TimeSpan.Parse("12:30:22") + TimeSpan.Parse("11:20:22");
Finally, your example as dates (not tested!):
var result = DateTime.Parse("12:30:22") + DateTime.Parse("11:20:22");
Note that this is sloppy coding, but you get the idea. You need to verify somehow that the string is actually parseable.
Not really sure what you're after, but can you not just use the built in functions to C#'s DateTime object?
DateTime myDate = DateTime.Now;
myDate = myDate.AddHours(1);
myDate = myDate.AddMinutes(30);
myDate = myDate.AddSeconds(45);
The problem is more abstract. As already mentioned, in .NET there are two types - DateTime and TimeSpan. The DateTime type represents a specific point in time. It's not an interval of time. It's a specific location in all time since the birth of the Universe. Even if you set the year/month/day components to 0, it will still represent some absolute point in time. Not a length of time.
The TimeSpan on the other hand represents some interval. 1 minute, 2 days, whatever. It's not specified WHEN, just HOW LONG.
So if you were to subtract two DateTime objects you would get a TimeSpan object that specifies how much time there is between them. And if you add a TimeSpan to a DateTime you get another DateTime. But you can't add a DateTime to another DateTime - that would make no sense.
It sounds to me like you should be working with TimeSpans all the time, because you are dealing with lengths of time, not absolute points in time. If you get these lengths from your source as a DateTime then that's actually not correct, and you should convert them to TimeSpans somehow. The parsing method is one way that has been suggested, but you might also try to subtract zero DateTime from it. That might be faster and more culture-independant.
use the TimeSpan structure. you can add TimeSpans together, or you can add a TimeSpan to a DateTime to produce a new DateTime.
You should have a look at TimeSpan.Parse. This converts a string to a TimeSpan object. That way you can do stuff like
TimeSpan a = TimeSpan.Parse(timeStringA)+TimeSpan.Parse(TimeStringB);
To split a string like "00:00:20+00:01:00" look at string.split
stringA = timeSting.split('+')[0];
stringb = timeSting.split('+')[1];
return string.Format("{0}:{1}:{2}", mytimespan.Hours
+ (mytimespan.Days*24),mytimespan.Minutes,mytimespan.Seconds);
static void Main(string[] args)
{
String timeText = "3/23/2015 12:00:13 AM";
String timeText2 = "3/23/2015 1:45:03 AM";
DateTime time = Convert.ToDateTime(timeText);
string temp = time.ToString("HH:mm:ss");
DateTime time2 = Convert.ToDateTime(timeText2);
string temp2 = time2.ToString("HH:mm:ss");
TimeSpan t1 = TimeSpan.Parse(temp);
TimeSpan t2 = TimeSpan.Parse(temp2);
Console.Out.WriteLine(t1 + t2); // 01:45:16
Console.ReadLine();
}

Categories