Timestamp in .NET.
I need to work with dates and times in my .NET project and one of the things I need to do is get the current date and add 2 weeks to it, and if the date is entered by the user after those 2 weeks throw an error. Or, if the date they entered before the current date throws another error.
Now I know how to do this, but not with the way .NET handles dates. I've only actually worked with timestamps in the past (probably because everything I've done in the past has been on Unix) and .NET doesn't seem to have a timestamp for handling date or time.
Can anyone tell me how I will do this?
Thank.
source to share
DateTime value = ...your code...
DateTime today = DateTime.Today, max = today.AddDays(14);
if(value < today || value > max) {
throw new ArgumentOutOfRangeException("value");
}
One key point: only access Now
/ Today
once per linked check - otherwise you might get some very bizarre results only at the midnight tick. The extreme edge, perhaps ...
source to share
There is a class in the .NET class DateTime
, but I really don't know what you mean by ".NET has no timestamps to handle date". Do you mean a way to generate or work with Unix timestamps?
To convert Unix timestamp to DateTime, you can do this:
DateTime epoch = new DateTime(1970, 1, 1); epoch = epoch.AddSeconds(timestamp);
To add two weeks, you must use the method AddDays
.
// Whatever class is able to retrieve the date the user just entered
DateTime userDateTime = Whatever.GetUserDateTime();
if (userDateTime > DateTime.Now.AddDays(14))
throw new Exception("The date cannot be after two weeks from now");
else if (userDateTime < DateTime.Now)
throw new Exception("The date cannot be before now");
source to share