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.

+2


source to share


6 answers


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 ...

+4


source


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

.

+1


source


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

      

+1


source


Why not just use

if (objUserDate.Date > DateTime.Today.AddDays(14))
{
     //Error 1
}
else if (objUserDate.Date < DateTime.Today)
{
    //Error 2
}

      

+1


source


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

      

0


source


I would probably have something like this:

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

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

      

0


source







All Articles