How to get a DateTime from total amount of seconds? - c#

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);

Related

offset datetime with each other - Must tell the number of days in total

I must have built up such that I have a datetime which gets added antale day as it should go forward. and then I have time as it should set off in relation to 04/10/16 to 10/09/16
I do not care about the time which is in datetime. It should not I use for anything. What I need out of this is exactly how many days there are from that time.
Datetime dateString = "4/10/2016 8:30:52" //I pretend that it comes from the database, it was more in terms of see what come there.
DateTime dt = DateTime.Now.AddDays(5);
What I need out of this is that it tell me how many days there are in between the two datetime as I entered.
You can substract DateTime objects to obtain a TimeSpan:
Datetime dateString = DateTime.Parse("4/10/2016 8:30:52");
DateTime dt = DateTime.Now;
TimeSpan duration = dt-dateString;
From the TimeSpan object, you can get how many (full) days with :
int totalCompleteDays = (int)duration.TotalDays;
Or if you want a rounded results :
int roundedTotalDays = (int)Math.Round(duration.TotalDays);
DateTime objects support basic operators and will return TimeSpan objects.
DateTime DateTimeB = DateTime.Now.AddDays(5);
DateTime DateTimeA = DateTime.Now;
TimeSpan difference = DateTimeA - DateTimeB;
...
you can then use the TotalDays property of the timeSpan.
...
Console.out.WriteLine(difference.TotalDays);

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;

How do I convert a 12 hour time string into a C# TimeSpan?

When a user fills out a form, they use a dropdown to denote what time they would like to schedule the test for. This drop down contains of all times of the day in 15 minute increments in the 12 hour AM/PM form. So for example, if the user selects 4:15 pm, the server sends the string "4:15 PM" to the webserver with the form submittion.
I need to some how convert this string into a Timespan, so I can store it in my database's time field (with linq to sql).
Anyone know of a good way to convert an AM/PM time string into a timespan?
You probably want to use a DateTime instead of TimeSpan. You can use DateTime.ParseExact to parse the string into a DateTime object.
string s = "4:15 PM";
DateTime t = DateTime.ParseExact(s, "h:mm tt", CultureInfo.InvariantCulture);
//if you really need a TimeSpan this will get the time elapsed since midnight:
TimeSpan ts = t.TimeOfDay;
Easiest way is like this:
var time = "4:15 PM".ToTimeSpan();
.
This takes Phil's code and puts it in a helper method. It's trivial but it makes it a one line call:
public static class TimeSpanHelper
{
public static TimeSpan ToTimeSpan(this string timeString)
{
var dt = DateTime.ParseExact(timeString, "h:mm tt", System.Globalization.CultureInfo.InvariantCulture);
return dt.TimeOfDay;
}
}
Try this:
DateTime time;
if(DateTime.TryParse("4:15PM", out time)) {
// time.TimeOfDay will get the time
} else {
// invalid time
}
I like Lee's answer the best, but acermate would be correct if you want to use tryparse. To combine that and get timespan do:
public TimeSpan GetTimeFromString(string timeString)
{
DateTime dateWithTime = DateTime.MinValue;
DateTime.TryParse(timeString, out dateWithTime);
return dateWithTime.TimeOfDay;
}
Try:
string fromServer = <GETFROMSERVER>();
var time = DateTime.Parse(fromServer);
That gets you the time, if you create the end time as well you can get Timespans by doing arithmetic w/ DateTime objects.

How can I get the offset as a TimeSpan if I only have the time as a string, such as 09:00 AM

I have the string "9:00 AM". I would like to get the offset from midnight as a TimeSpan in C#?
9:00 AM is a punctual time, while TimeSpan structure represents time intervals so you are trying to convert apples to oranges.
Timespan? A timespan is just a period of time. The "AM" shows that this is a specific time, so this cannot be a timespan. Or do you want to parse "9:00", without the "AM", and get a timespan of 9 hours as result?
#Your comment:
You could use a method that does this for you. Here's a simple example implementation (you would need to add better input validation, use better convert methods than just Convert.ToInt32() and so on):
public static TimeSpan GetTimeSpanFormString(string strString)
{
strString = strString.Trim();
string[] strParts = strString.Split(':', ' ');
int intHours, intMinutes;
if (strParts.Length != 3)
throw new ArgumentException("The string is not a valid timespan");
intHours = strParts[2].ToUpper() == "PM" ? Convert.ToInt32(strParts[0]) + 12 : Convert.ToInt32(strParts[0]);
intMinutes = Convert.ToInt32(strParts[1]);
return new TimeSpan(intHours, intMinutes, 0);
}
If you want the offset from midnight, you can use:
DateTime dateTime = DateTime.ParseExact( strValue, "h:mm tt" );
TimeSpan offset = dateTime - DateTime.Today;
TimeSpan.TryParse(yourString, out yourTimeSpan);

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