Sreejith Sree
Sreejith Sree

Reputation: 3766

Xamarin forms: Get the next and previous dates with a selected date

I am using the following codes for getting the next and previous day details with a selected day. I have 2 buttons named next and previous for getting the next previous dates.

//Saving the current date
string selectedDate = DateTime.Now.ToString("dd-MM-yyyy");

//Previous day
public void PrevButtonClicked(object sender, EventArgs args)
{
   DateTimeOffset dtOffset;
   if (DateTimeOffset.TryParse(selectedDate, null, DateTimeStyles.None, out dtOffset))
   {
      DateTime myDate = dtOffset.DateTime;
      selectedDate = myDate.AddDays(-1).ToString("dd-MM-yyyy");
   }
}
//Next day
public void NextButtonClicked(object sender, EventArgs args)
{
    DateTimeOffset dtOffset;
    if (DateTimeOffset.TryParse(selectedDate, null, DateTimeStyles.None, out dtOffset))
    {
       DateTime myDate = dtOffset.DateTime;
       selectedDate = myDate.AddDays(+1).ToString("dd-MM-yyyy");
     }
 }

If I click the previous button I get 03-04-2019 as the result. If again pressed the previous button I get 02-10-2019. Same for the next buttons. Based on the selected date, it will return the next or previous date.

This feature working perfectly in android and windows. But in ios getting the wrong result with this code. Is this the correct way of achieving this feature?

Upvotes: 0

Views: 468

Answers (1)

Lucas Zhang
Lucas Zhang

Reputation: 18861

You can improve your code . I create a sample with a Label to display the current date.

in xaml

<StackLayout VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" Orientation="Horizontal">
       
    <Button Text="Preview" Clicked="PrevButtonClicked"/>

    <Label x:Name="dateLabel" TextColor="Red" WidthRequest="100"/>

    <Button Text="Next"  Clicked="NextButtonClicked"/>

</StackLayout>

in code Behind

public partial class MainPage : ContentPage
{
  int year, month, day;

  public MainPage()
  {
     InitializeComponent();

     dateLabel.Text = DateTime.Now.ToString("dd-MM-yyyy");

     year = DateTime.Now.Year;
     month = DateTime.Now.Month;
     day= DateTime.Now.Day;
  }

  private void Button_Clicked(object sender, EventArgs e)
  {
    DateTime nowDate = new DateTime(year, month, day);

    var previewDate = nowDate.AddDays(-1);

    dateLabel.Text = previewDate.ToString("dd-MM-yyyy");

    year = previewDate.Year;
    month = previewDate.Month;
    day = previewDate.Day;
  }

  private void Button_Clicked_1(object sender, EventArgs e)
  {
     DateTime nowDate = new DateTime(year, month, day);

     var nextDate = nowDate.AddDays(+1);

     dateLabel.Text = nextDate.ToString("dd-MM-yyyy");

     year = nextDate.Year;
     month = nextDate.Month;
     day = nextDate.Day;
  }
}

enter image description here

Upvotes: 2

Related Questions