Sunny Sandeep
Sunny Sandeep

Reputation: 1011

how to set date in second textbox according to first textbox date in asp.net

I am working on an asp.net application where i have two textbox for selection two date as Fromdate and EndDate. I have also two calender extender for both textbox whose Format is dd/MM/yyyy. If i select any date in First textbox "txtFromDate" using calender extender then it will calculate that if it is minimum 7 days smaller than today date then second textbox will automatically set to 7 days after the date of first textbox date. If the difference between today date and first textbox date is less than 7 then second textbox should show today date in second textbox. For this i used the following code on first textbox textchanged event

DateTime dt1, dt2, dt3;

dt1 = Convert.ToDateTime(txtStartDate.Text);
dt2 = Convert.ToDateTime(DateTime.Today);
dt3 = dt1.AddDays(7);
TimeSpan s = dt2 - dt1;
int x = (int)s.TotalHours;
x = x / 24;
if (x >= 7)
{
    txtEndDate.Text = dt3.ToShortDateString();
}
else
{
    txtEndDate.Text = dt2.ToShortDateString();
}

Here if i select 22/05/2018 then second textbox should show 29/05/2018 but it is showing 29-May-18. How to solve it?

Upvotes: 0

Views: 1135

Answers (3)

Balaji G
Balaji G

Reputation: 53

Try This Code :

String.Format("{0:MM/dd/yyyy}", YourDate); 

Ref : http://www.csharp-examples.net/string-format-datetime/

Upvotes: 1

sujith karivelil
sujith karivelil

Reputation: 29036

Few things you are doing wrong here:

  • datetime.today property gives you a DateTime object you need not to convert this again to DateTime.
  • To get number of days between two dates you need not to get total hours then divide it by 24, you can simply use TotalDaysproperty.
  • Better to use Parsing instead for Convert.ToDateTime to avoid FormatException

So the modified code will be like the following:

var diffInDays = (dt2-dt1).TotalDays;   
if (diffInDays >= 7)
{
     txtEndDate.Text = dt3.ToShortDateString();
}
else
{
     txtEndDate.Text = dt2.ToShortDateString();
}

If the issue you are facing is the format of the date displaying in txtEndDate then you can use the .ToString("Format-here") as like other answers suggests. For example : txtEndDate.Text = dt2.ToString("dd/MM/yyyy");

Upvotes: 0

RichardMc
RichardMc

Reputation: 854

Explicitly state your format instead of using ToShortDateString(). Use the following instead:

.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

Upvotes: 1

Related Questions