I am programming small page and I want to display expiration time of authentication ticket. I mean not the end, but remaining time. Current code is follows:
DateTime cas = (DateTime)ticket.Expiration.Date;
DateTime cas1 = DateTime.Now;
DateTime cas2 = cas1.Subtract(cas);
However, VS says "Cannot implicitly convert system.timespan into system datetime".
Pls help. Thanks a lot.
Substract method returns a timespan, not a Datetime. Try this :
Timespan cas2 = cas.Subtract(cas1);
[edit] following the comments, the code that should works is simply :
TimeSpan remaining = ticket.Expiration.Substract(DateTime.Now);
You don't have to case Expiration, as it's a DateTime property.
You can use operator overloading. The type returned by subtracting one DateTime from another is a TimeSpan:
TimeSpan remainingTime = ticket.Expiration - DateTime.Now;
Related
I'm trying to get today's date
DateTime todayDateTime = new DateTime();
and I'm getting this:
{1/1/0001 12:00:00 AM}.
Why is this happening?
Use this
DateTime date = DateTime.Now;
Using new DateTime() creates a DateTime with a time of "0".
If you want todays date you need to use DateTime.Today if you want a DateTime object with a date of today and a time of 12:00:00 AM or DateTime.Now if you want a DateTime with the day and time of the moment you called DateTime.Now.
According to MSDN, the constructor for DateTime which takes in a long initializes by using the specified number of ticks since January 1st, 0001, so saying new DateTime(0) yields this time, not the current time.
Instead, use the static field DateTime.Now to get a DateTime representing the current system time.
In your question you are just initializing the Variable todayDateTime but you have never assigned (set it). This is why it is date ("null")/ beginning of our time calculations.
To actually get todays Date, you can use the following:
DateTime today = DateTime.Today;
first of all you need to assigned a value in the datetime.
just use something like this :
DateTime today = DateTime.Today;
I want to convert a Timespan to Datetime. How can I do this?
I found one method on Google:
DateTime dt;
TimeSpan ts="XXX";
//We can covnert 'ts' to 'dt' like this:
dt= Convert.ToDateTime(ts.ToString());
Is there any other way to do this?
It is not very logical to convert TimeSpan to DateTime. Try to understand what leppie said above. TimeSpan is a duration say 6 Days 5 Hours 40 minutes. It is not a Date. If I say 6 Days; Can you deduce a Date from it? The answer is NO unless you have a REFERENCE Date.
So if you want to convert TimeSpan to DateTime you need a reference date. 6 Days & 5 Hours from when? So you can write something like this:
DateTime dt = new DateTime(2012, 01, 01);
TimeSpan ts = new TimeSpan(1, 0, 0, 0, 0);
dt = dt + ts;
While the selected answer is strictly correct, I believe I understand what the OP is trying to get at here as I had a similar issue.
I had a TimeSpan which I wished to display in a grid control (as just hh:mm) but the grid didn't appear to understand TimeSpan, only DateTime . The OP has a similar scenario where only the TimeSpan is the relevant part but didn't consider the necessity of adding the DateTime reference point.
So, as indicated above, I simply added DateTime.MinValue (though any date will do) which is subsequently ignored by the grid when it renders the timespan as a time portion of the resulting date.
TimeSpan can be added to a fresh DateTime to achieve this.
TimeSpan ts="XXX";
DateTime dt = new DateTime() + ts;
But as mentioned before, it is not strictly logical without a valid start date. I have encountered
a use-case where i required only the time aspect. will work fine as long as the logic is correct.
You need a reference date for this to be useful.
An example from
http://msdn.microsoft.com/en-us/library/system.datetime.add.aspx
// Calculate what day of the week is 36 days from this instant.
System.DateTime today = System.DateTime.Now;
System.TimeSpan duration = new System.TimeSpan(36, 0, 0, 0);
System.DateTime answer = today.Add(duration);
System.Console.WriteLine("{0:dddd}", answer);
Worked for me.
var StartTime = new DateTime(item.StartTime.Ticks);
If you only need to show time value in a datagrid or label similar, best way is convert directly time in datetime datatype.
SELECT CONVERT(datetime,myTimeField) as myTimeField FROM Table1
You could also use DateTime.FromFileTime(finishTime) where finishTme is a long containing the ticks of a time. Or FromFileTimeUtc.
An easy method, use ticks:
new DateTime((DateTime.Now - DateTime.Now.AddHours(-1.55)).Ticks).ToString("HH:mm:ss:fff")
This function will give you a date (Without Day / Month / Year)
A problem with all of the above is that the conversion returns the incorrect number of days as specified in the TimeSpan.
Using the above, the below returns 3 and not 2.
Ideas on how to preserve the 2 days in the TimeSpan arguments and return them as the DateTime day?
public void should_return_totaldays()
{
_ts = new TimeSpan(2, 1, 30, 10);
var format = "dd";
var returnedVal = _ts.ToString(format);
Assert.That(returnedVal, Is.EqualTo("2")); //returns 3 not 2
}
First, convert the timespan to a string, then to DateTime, then back to a string:
Convert.ToDateTime(timespan.SelectedTime.ToString()).ToShortTimeString();
Hi I have a local variable of the type of System.DateTime. How can I get just the time? Thanks
DateTime.Now.TimeOfDay returns a TimeSpan representing the time of the day.
If this is for display purposes (As it normally is with these questions), you can simply use one of the following:
myDateTime.ToShortTimeString();
myDateTime.ToString("hh:mm:ss"); //for 12 hour clock
myDateTime.ToString("HH:mm:ss"); //for 24 hour clock
DateTime time = DateTime.Now.TimeOfDay
DateTime dt = DateTime.Now;
string time_now =dt.TimeOfDay.ToString();
Is there any easy way to get a DateTime's "TimeMin" and "TimeMax"?
TimeMin: The very first moment of the day. There is no DateTime that occurs before this one and still occurs on the same day.
TimeMax: The very last moment of the day. There is no DateTime that occurs after this one and still occurs on the same day.
These values would be helpful for filtering and doing date-related queries.
Here are two extensions I use to do exactly that.
/// <summary>
/// Gets the 12:00:00 instance of a DateTime
/// </summary>
public static DateTime AbsoluteStart(this DateTime dateTime)
{
return dateTime.Date;
}
/// <summary>
/// Gets the 11:59:59 instance of a DateTime
/// </summary>
public static DateTime AbsoluteEnd(this DateTime dateTime)
{
return AbsoluteStart(dateTime).AddDays(1).AddTicks(-1);
}
This allows you to write:
DateTime.Now.AbsoluteEnd() || DateTime.Now.AbsoluteStart()
or
DateTime partyTime = new DateTime(1999, 12, 31);
Console.WriteLine("Start := " + partyTime.AbsoluteStart().ToString());
Console.WriteLine("End := " + partyTime.AbsoluteEnd().ToString());
I'd use the following:
DateTime now = DateTime.Now;
DateTime startOfDay = now.Date;
DateTime endOfDay = startOfDay.AddDays(1);
and use < endOfDay instead of <= endOfDay. This will mean that it will work regardless of whether the precision is minutes, seconds, milliseconds, ticks, or something else. This will prevent bugs like the one we had on StackOverflow (though the advice was ignored).
Note that it is important to only call DateTime.Now once if you want the start and end of the same day.
try
//midnight this morning
DateTime timeMin = DateTime.Now.Date;
//one tick before midnight tonight
DateTime timeMax = DateTime.Now.Date.AddDays(1).AddTicks(-1)
If you are using this for filtering, as your comments suggest, it is probably a good idea to save DateTime.Now into a variable, just in case the date ticks over between the two calls. Very unlikely but call it enough times and it will inevitably happen one day (night rather).
DateTime currentDateTime = DateTime.Now;
DateTime timeMin = currentDateTime.Date;
DateTime timeMax = currentDateTime.Date.AddDays(1).AddTicks(-1)
One small tweak to hunter's solution above...
I use the following extension method to get the end of the day:
public static DateTime EndOfDay(this DateTime input) {
return input.Date == DateTime.MinValue.Date ? input.Date.AddDays(1).AddTicks(-1) : input.Date.AddTicks(-1).AddDays(1);
}
This should handle cases where the DateTime is either DateTime.MinValue or DateTime.MaxValue. If you call AddDays(1) on DateTime.MaxValue, you will get an exception. Similarly, calling AddTicks(-1) on DateTime.MinValue will also throw an exception.
You must be careful to use
(new DateTime()).AddDays(1).AddTicks(-1);
when it is passed to stored procedure.
It could happen that the value will be approximated to next day.
Like other answerers, I'm not quite sure what you're asking for, but incase you want the smallest possible time and the largest possible time, (not just in a day), then there's DateTime.MinValue and DateTime.MaxValue which return 1/1/0001 12:00:00 AM
and 12/31/9999 11:59:59 PM respectively.
I would advise that you look at this answer:
How can I specify the latest time of day with DateTime
If your original DateTimes also potentially include times, using the AddDays() method will add a full 24 hours, which may not be precisely what you want.
public static DateTime ToEndOfDay(this DateTime time)
{
var endOfDaySpan = TimeSpan.FromDays(1).Subtract(TimeSpan.FromMilliseconds(1));
return time.Date.Add(endOfDaySpan);
}
Please note that if you're passing this time to sql server you should use
dateTime.Date.AddDays(1).AddMilliseconds(-3);
See:
How do I get the last possible time of a particular day
DateTime.Today.AddDays(1).AddSeconds(-1);
Not very exact, but fixed my problems. Now we can use AddMilliseconds, AddTicks and etc. I think it will just vary on what would satisfy your need.
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();
}