tags:

views:

140

answers:

6
+2  Q: 

Timestamp in .NET

I have 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 onto it, and if the date the user entered is after those two weeks throw out an error. Or, if the date they entered is before the current date throw out another error.

Now, I know how to do this, but not with the way .NET seems to handle dates. I have 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 way of handling the date or time.

Can anyone tell me how I would go about this?

Thank you.

+1  A: 

There's the DateTime class in .NET, but I don't really know what you mean by ".NET doesn't have a timestamp way of handling the date." Do you mean a way to generate or work with Unix timestamps?

To convert a Unix timestamp to a DateTime, you could do this:

DateTime epoch = new DateTime(1970, 1, 1);
epoch = epoch.AddSeconds(timestamp);

To add two weeks, you would use the AddDays method.

nasufara
A: 
var userInputDate = DateTime.Parse(someInput);

if(userInputDate > DateTime.Now.AddDays(14)) throw new ApplicationException("Dont like dates after 2 weeks of today");
if(userInputDate < DateTime.Now) throw new ApplicationException("Date shouldnt be before now, for some reason");
Owen
+1  A: 
            // 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");
Ciwee
+4  A: 
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 in a related check - otherwise you can get some very freaky results just on the stroke of midnight. An extreme edge-case, maybe...

Marc Gravell
+1  A: 

Why not just use

if (objUserDate.Date > DateTime.Today.AddDays(14))
{
     //Error 1
}
else if (objUserDate.Date < DateTime.Today)
{
    //Error 2
}
Maximilian Mayerl
+1 For using DateTime.Today. If the time of day isn't relevant, it shouldn't be included in the calculations.
Joren
A: 

i would probably have something like this:

DateTime twoWeeksFromNow = DateTime.Now.AddDays(14);

if(enteredDateTime > twoWeeksFromNow)
{
    throw "ERROR!!!";
}
John Boker