开发者

Timestamp in .NET

开发者 https://www.devze.com 2022-12-09 22:38 出处:网络
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 th

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 wou开发者_如何学Pythonld go about this?

Thank you.


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


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.


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


Why not just use

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


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


i would probably have something like this:

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

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

精彩评论

暂无评论...
验证码 换一张
取 消