UWP Development, Date and Time

Universal Windows Platform (UWP) development is a powerful way to create modern Windows applications. Today, we will explain in detail how to handle dates and times in UWP. To aid in a deep understanding, we will include UWP’s date and time-related APIs, available data formats, example code, and practical tips.

1. Importance of Date and Time

Dates and times are critical elements in most applications. User activity logs, event schedules, timers, and many other functions are based on dates and times. UWP offers various classes and methods for managing dates and times. By using these classes, developers can easily manipulate dates and times in the desired format.

2. Classes for Handling Dates and Times in UWP

2.1. DateTime Class

The DateTime class is the most fundamental class representing dates and times. This class provides functionalities for date and time calculations, formatting, and comparisons.

2.1.1. Creating a DateTime

A DateTime object can be created using various constructors. Here are a few examples:

using System;

DateTime now = DateTime.Now; // Current date and time
DateTime specificDate = new DateTime(2023, 10, 1); // Specific date
DateTime withTime = new DateTime(2023, 10, 1, 15, 30, 0); // Specific date and time

2.1.2. Formatting Date and Time

You can specify the format when converting a DateTime object to a string. Here are examples of formatting:

using System;

DateTime date = new DateTime(2023, 10, 1);
string formattedDate = date.ToString("yyyy-MM-dd"); // "2023-10-01"
string formattedTime = date.ToString("HH:mm:ss"); // "00:00:00"

2.2. TimeSpan Class

The TimeSpan class represents the interval of time between two dates. It allows developers to calculate or compare time intervals.

2.2.1. Creating a TimeSpan

using System;

TimeSpan duration = new TimeSpan(1, 30, 0); // 1 hour 30 minutes
TimeSpan difference = new DateTime(2023, 10, 1) - new DateTime(2023, 9, 30); // 1 day

2.2.2. Using TimeSpan

A TimeSpan object provides several useful properties and methods:

using System;

TimeSpan timeSpan = new TimeSpan(2, 30, 0); // 2 hours 30 minutes
int totalHours = (int)timeSpan.TotalHours; // Total hours
int totalMinutes = (int)timeSpan.TotalMinutes; // Total minutes

3. Using Date and Time APIs

3.1. DateTimeOffset Class

The DateTimeOffset class represents a specific time zone and specifies the difference from UTC (Coordinated Universal Time). This allows accurate date and time information for different time zones.

3.1.1. Example Usage

using System;

DateTimeOffset dateTimeOffset = DateTimeOffset.Now; // Current date and time
Console.WriteLine(dateTimeOffset); // Example: 2023-10-01 15:30:00 +09:00

3.2. Using Date Picker

In UWP apps, DatePicker and TimePicker controls can be used to allow users to select dates and times. These two controls make it easy for the user interface to select dates and times.

3.2.1. Adding Date and Time Pickers via XAML

Here is the XAML code to add a DatePicker and a TimePicker to the UI:

<StackPanel>
    <TextBlock Text="Select Date:" />
    <DatePicker x:Name="datePicker" />

    <TextBlock Text="Select Time:" />
    <TimePicker x:Name="timePicker" />
</StackPanel>

3.2.2. Handling Selected Date and Time

Here is an example of C# code for handling the selected date and time:

using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

// Assume: datePicker and timePicker are defined in XAML
public MainPage()
{
    this.InitializeComponent();
    datePicker.DateChanged += DatePicker_DateChanged;
    timePicker.TimeChanged += TimePicker_TimeChanged;
}

private void DatePicker_DateChanged(object sender, DatePickerValueChangedEventArgs e)
{
    DateTime selectedDate = e.NewDateTime.Date;
    // Additional logic for the selected date
}

private void TimePicker_TimeChanged(object sender, TimePickerValueChangedEventArgs e)
{
    TimeSpan selectedTime = e.NewTime;
    // Additional logic for the selected time
}

4. Manipulating Dates and Times

UWP offers various ways to quickly manipulate dates and times. Below, we will introduce methods for adding and subtracting date and time or comparing them.

4.1. Adding Dates and Times

using System;

DateTime today = DateTime.Now;
DateTime nextWeek = today.AddDays(7); // One week later
DateTime nextHour = today.AddHours(1); // One hour later

4.2. Subtracting Dates and Times

using System;

DateTime today = DateTime.Now;
DateTime previousWeek = today.AddDays(-7); // One week ago
DateTime previousHour = today.AddHours(-1); // One hour ago

4.3. Comparing Dates and Times

using System;

DateTime date1 = new DateTime(2023, 10, 1);
DateTime date2 = new DateTime(2023, 10, 15);

if (date1 < date2)
{
    Console.WriteLine("date1 is earlier than date2.");
}
else if (date1 > date2)
{
    Console.WriteLine("date1 is later than date2.");
}
else
{
    Console.WriteLine("date1 and date2 are the same.");
}

5. Formatting Dates and Times

UWP provides ways to represent dates and times in various formats. Users can specify formats as needed to provide easily readable date and time information.

5.1. Default Format

using System;

DateTime date = DateTime.Now;
string defaultFormat = date.ToString(); // Default format
string customFormat = date.ToString("dddd, dd MMMM yyyy"); // Example: "Saturday, 01 October 2023"

5.2. Culture-based Formatting

UWP supports date and time formats tailored to various cultures. You can use CultureInfo to convert to a specific cultural format.

using System.Globalization;

CultureInfo cultureInfo = new CultureInfo("fr-FR");
string frenchDate = date.ToString(cultureInfo); // Representing date in French format

6. Example Project

Based on the above descriptions, let’s create a simple example project. This project is an application that inputs dates and times and displays the selected date and time.

6.1. XAML

<Page x:Class="DateTimeApp.MainPage">
    <Grid>
        <StackPanel>
            <TextBlock Text="Select Date:" />
            <DatePicker x:Name="datePicker" />

            <TextBlock Text="Select Time:" />
            <TimePicker x:Name="timePicker" />

            <Button Content="Show Info" Click="ShowInfo_Click" />

            <TextBlock x:Name="resultTextBlock" />
        </StackPanel>
    </Grid>
</Page>

6.2. C# Code

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace DateTimeApp
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        private void ShowInfo_Click(object sender, RoutedEventArgs e)
        {
            DateTime selectedDate = datePicker.DateTime.Date;
            TimeSpan selectedTime = timePicker.Time;

            string result = $"Selected Date: {selectedDate.ToString("yyyy-MM-dd")}" +
                            $"\nSelected Time: {selectedTime.Hours}:{selectedTime.Minutes}";

            resultTextBlock.Text = result;
        }
    }
}

7. Conclusion

In UWP development, dates and times are important elements. By leveraging the DateTime, TimeSpan, and DateTimeOffset classes, we can easily manage dates and times and provide functionalities for users to select dates and times. This article discussed in depth how to manipulate and display dates and times. Be sure to apply this to your real projects.

This concludes our overview of handling dates and times through UWP, and we hope it helps in developing practical applications!