Does c# have support for converting two DateTime's to the xs:duration data type? (I'm assuming I need two DateTime values for this?)
References: http://www.w3.org/TR/xmlschema-2/#duration and http://www.w3schools.com/schema/schema_dtypes_date.asp (half way down)
There was support for this in the XMLConvert class as explained here: http://kennethxu.blogspot.de/2008/09/xmlserializer-doesn-serialize-timespan.html
I ended up using this code and it displays the value in the xml correct
[XmlElementAttribute("ValidThrough", DataType = "duration")]
[DataMember(Name = "ValidThrough")]
[DefaultValue("P10D")]
public string ValidThrough
{
get
{
return XmlConvert.ToString(_validThroughField);
}
set
{
_validThroughField= XmlConvert.ToTimeSpan(value);
}
}
[XmlIgnore]
public TimeSpan _validThroughField { get; set; }
TimeSpan is what you are looking for.
A TimeSpan object represents a time interval (duration of time or
elapsed time) that is measured as a positive or negative number of
days, hours, minutes, seconds, and fractions of a second. The TimeSpan
structure can also be used to represent the time of day, but only if
the time is unrelated to a particular date. Otherwise, the DateTime or
DateTimeOffset structure should be used instead.
Example:
DateTime dt1 = new DateTime(2012, 10, 2, 10, 20, 00);
DateTime dt2 = DateTime.Now;
TimeSpan ts = dt1 - dt2;
Related
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);
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);
I use many DateTime in my code. I want to change those DateTimes to my specific date and keep
time.
1. "2012/02/02 06:00:00" => "2015/12/12 : 06:00:00"
2. "2013/02/02 12:00:00" => "2015/12/12 : 12:00:00"
I use this style to change, but it seem not the good way and I want to ask have any way to achieve this task.
DateTime newDateTime = new DateTime(2015,12,12,oldDateTime.Hour,oldDateTime.Minute,0);
A better way that preserves the seconds, milliseconds and smaller parts of the time would be:
DateTime newDateTime = new DateTime(2015,12,12) + oldDateTime.TimeOfDay;
Or you could make an extension method to apply a new Date to an existing DateTime and, at the same time, not trust the new date to be without a TimeOfDay on it:-
public static DateTime WithDate (this DateTime datetime, DateTime newDate)
{
return newDate.Date + datetime.TimeOfDay;
}
IMHO DateTime is one of the weakest parts of .NET. For example, a TimeSpan is not the same as a TimeOfDay nor can it represent a 'TimePeriod' (in months) - these are three separate concepts and mixing them up was a poor choice. Moving to DateTimeOffset is generally preferred or to the excellent Noda time library.
With the information you have given, I think this method is fine. If you want to avoid rewriting the oldDateTime.Hour,oldDateTime.Minute,0 piece often, you could create your own static class to simplify the method calls.
In your regular application:
class Program
{
static void Main(string[] args)
{
DateTime time = DateTime.Now;
DateTime newDateTime = MyDateTimeUtil.CreateDateFromTime(2015, 12, 12, time);
}
}
The static class that creates the DateTime value:
public static class MyDateTimeUtil
{
public static DateTime CreateDateFromTime(int year, int month, int day, DateTime time)
{
return new DateTime(year, month, day, time.Hour, time.Minute, 0);
}
}
Let's say I have a start DateTime object containing 2012/09/21 23:59:59 and an end DateTime object containing 2012/09/22 00:01:02. The difference between these two objects is little more than a minute, but the number of days belonging to this range of dates is equal to 2.
I have read other similar questions, and I think that TimeSpan and DateTime classes do not provide methods to perform this type of calculation. How to calculate the number of days belonging to a certain range of dates?
Use:
DateTime dateTime1 = DateTime.Parse("2012/09/21 23:59:59");
DateTime dateTime2 = DateTime.Parse("2012/09/22 00:01:02");
TimeSpan difference = dateTime1 - dateTime2;
The variable difference contains the time between the two dates. For example use the TotalDays property to get the difference in days.
If you want to exclude the time portion, use the Date property on DateTime, for example:
TimeSpan difference = dateTime1.Date - dateTime2.Date;
TotalDays will be 1 in this case rather than 0.
You can do the following:
System.DateTime dtTodayNoon = new System.DateTime(2006, 9, 13, 12, 0, 0);
System.DateTime dtTodayMidnight = new System.DateTime(2006, 9, 13, 0, 0, 0);
System.TimeSpan diffResult = dtTodayNoon.Subtract(dtYestMidnight);
Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.Days);
Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.TotalDays);
Console.ReadLine();
If you want to include the daylight savings:
System.TimeSpan diffResult = dtTodayNoon.ToUniversalTime().Subtract(dtYestMidnight.ToUniversalTime());
You could use DateTimeOffSet too if timezones are important
Doesn't
(dateTime2 - dateTime1).TotalDays
work for you?
I have read other similar questions, and I think that TimeSpan and
DateTime classes do not provide methods to perform this type of
calculation.
Of course that they do.
TimeSpan is the class to use. I guess you are looking for the TotalDays property, aren't you?
DateTime date1 = ...;
DateTime date2 = ...;
TimeSpan difference = date2 - date1;
int totalNumberOfDays = difference.TotalDays;
I'm trying to put together a tool that will help me make work schedules. What is the easiest way to solve the following?
8:00am + 5 hours = 1:00pm
5:00pm - 2 hours = 3:00pm
5:30pm - :45 = 4:45
and so on.
These can all be done with DateTime.Add(TimeSpan) since it supports positive and negative timespans.
DateTime original = new DateTime(year, month, day, 8, 0, 0);
DateTime updated = original.Add(new TimeSpan(5,0,0));
DateTime original = new DateTime(year, month, day, 17, 0, 0);
DateTime updated = original.Add(new TimeSpan(-2,0,0));
DateTime original = new DateTime(year, month, day, 17, 30, 0);
DateTime updated = original.Add(new TimeSpan(0,-45,0));
Or you can also use the DateTime.Subtract(TimeSpan) method analogously.
Check out all the DateTime methods here: http://msdn.microsoft.com/en-us/library/system.datetime.aspx
Add Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance.
AddDays Returns a new DateTime that adds the specified number of days to the value of this instance.
AddHours Returns a new DateTime that adds the specified number of hours to the value of this instance.
AddMilliseconds Returns a new DateTime that adds the specified number of milliseconds to the value of this instance.
AddMinutes Returns a new DateTime that adds the specified number of minutes to the value of this instance.
AddMonths Returns a new DateTime that adds the specified number of months to the value of this instance.
AddSeconds Returns a new DateTime that adds the specified number of seconds to the value of this instance.
AddTicks Returns a new DateTime that adds the specified number of ticks to the value of this instance.
AddYears Returns a new DateTime that adds the specified number of years to the value of this instance.
This works too:
System.DateTime dTime = DateTime.Now();
// tSpan is 0 days, 1 hours, 30 minutes and 0 second.
System.TimeSpan tSpan = new System.TimeSpan(0, 1, 3, 0);
System.DateTime result = dTime + tSpan;
To subtract a year:
DateTime DateEnd = DateTime.Now;
DateTime DateStart = DateEnd - new TimeSpan(365, 0, 0, 0);
Hi if you are going to subtract only Integer value from DateTime then you have to write code like this
DateTime.Now.AddHours(-2)
Here I am subtracting 2 hours from the current date and time
Use the TimeSpan object to capture your initial time element and use the methods such as AddHours or AddMinutes. To substract 3 hours, you will do AddHours(-3). To substract 45 mins, you will do AddMinutes(-45)
try this
namespace dateandtime
{
class DatesTime
{
public static DateTime Substract(DateTime now, int hours,int minutes,int seconds)
{
TimeSpan T1 = new TimeSpan(hours, minutes, seconds);
return now.Subtract(T1);
}
static void Main(string[] args)
{
Console.WriteLine(Substract(DateTime.Now, 36, 0, 0).ToString());
}
}
}
TimeLeftToOpen= new TimeSpan(TimeLeftToOpen.Hours, TimeLeftToOpen.Minutes, TimeLeftToOpen.Seconds - 1);