Reputation: 11
This is probably a very basic question for you guys, but I'm new to this world and try to learn everyday. I have added some columns in the standard dbo.AspNetUsers table. One of them is a date which I want to compare with the current DateTime. The date from the database needs to be in the future, otherwise it should not be allowed to view the page.
I've tried somethings in my controllers:
public string LicenseDate { get; set; }
public string CurrentDate = DateTime.Now.ToString("dd-MM-yyyy");
public ActionResult Index()
if ((LicenseDate.Date - DateTime.Today).Days > 1)
{ do someting }
else
return RedirectToAction("../Home/Buy");
Can someone point me in the right direction? thanks!
Upvotes: 1
Views: 1924
Reputation: 11
Thanks everybody for your suggestions! I tried some options and I don't have any bugs left. But it is not working since I think the LicenseDate is not 'loaded' from the database well. It looks like the current date is compared with the current date :) I made sure that my field in the database is a Datetime type and is declared at the start:
public DateTime LicenseDate { get; set; }
This is how my table looks like:
CREATE TABLE [dbo].[AspNetUsers] (
[Id] NVARCHAR (128) NOT NULL,
[UserName] NVARCHAR (MAX) NULL,
[PasswordHash] NVARCHAR (MAX) NULL,
[SecurityStamp] NVARCHAR (MAX) NULL,
[Name] NVARCHAR (MAX) NULL,
[Surname] NVARCHAR (MAX) NULL,
[Company] NVARCHAR (MAX) NULL,
[Street] NVARCHAR (MAX) NULL,
[ZIPcode] NVARCHAR (MAX) NULL,
[City] NVARCHAR (MAX) NULL,
[Country] NVARCHAR (MAX) NULL,
[Phone] NVARCHAR (MAX) NULL,
[Email] NVARCHAR (MAX) NULL,
[Discriminator] NVARCHAR (128) NOT NULL,
[IPAddress] NVARCHAR (MAX) NULL,
[RegisterDate] DATETIME NULL,
[LicenseDate] DATETIME NULL,
CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED ([Id] ASC)
);
Thanks again for looking into this.
Upvotes: 0
Reputation: 25370
I'd just use DateTime.Compare
:
if (DateTime.Compare(DateTime.Parse(LicenseDate.Date), DateTime.UtcNow) > 0)
{
//License Date Later
}
else
{
//License Date Equal To Or Earlier
}
Assuming LicenseDate
is a valid Date string.
Upvotes: 1
Reputation: 1333
public System.DateTime current = System.DateTime.Now;
public System.DateTime Licensedate {get; set}
if( Licensedate.Subtract(current).TotalDays >1 ){
//... do somethink
}
Subtract Method which returns TimeSpan that has TotalDays property
Upvotes: 0
Reputation: 10430
A few things to note:
So, the following updated code should get you closer:
public string LicenseDate { get; set; }
public string CurrentDate = DateTime.Now.ToString("dd-MM-yyyy");
public ActionResult Index() {
var licenseDateTime = Convert.ToDateTime(LicenseDate);
if ((licenseDateTime.Subtract(DateTime.Today)).TotalDays > 1)
{
// do something
} else {
return RedirectToAction("../Home/Buy");
}
}
Hope that helps!
Upvotes: 0