我想用时间减去两个日期。最后,我会得到44天,14小时15分钟的东西。现在我只得到时间02:03:00(我不需要的秒数。)
我从datepicker和时间选择器中获取的日期和时间
Xaml代码
<StackPanel HorizontalAlignment="Left">
<!--<TextBlock x:Name="textblock" Text="textblock"/>-->
<DatePicker x:Name="datepicker1" Margin="10"/>
<TimePicker x:Name="timepicker1" Margin="10"/>
<DatePicker x:Name="datepicker2" Margin="10"/>
<TimePicker x:Name="timepicker2" Margin="10"/>
<Button x:Name="datumbutton" Click="datumbutton_Click" Content="Combine"/>
<TextBlock x:Name="datumtextblock" Margin="20" Text="datum" />
<TextBlock x:Name="datumtextblock2" Text="datum2"/>
<TextBlock x:Name="vysledek" Text="vysledek"/>
</StackPanel>
UWP代码
using Windows.Globalization;
using Windows.Globalization.DateTimeFormatting;
private void datumbutton_Click(object sender, RoutedEventArgs e)
{
DateTimeFormatter dateFormatter = new DateTimeFormatter("shortdate");
DateTimeFormatter timeFormatter = new DateTimeFormatter("shorttime");
Calendar calendar = new Calendar();
calendar.ChangeClock("24HourClock");
DateTimeOffset selectedDate = this.datepicker1.Date;
DateTimeOffset combinedValue = new DateTimeOffset(new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day) + this.timepicker1.Time);
DateTimeOffset selectedDate2 = this.datepicker2.Date;
DateTimeOffset combinedValue2 = new DateTimeOffset(new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day) + this.timepicker2.Time);
calendar.SetDateTime(combinedValue);
calendar.SetDateTime(combinedValue2);
datumtextblock.Text= ("Combined value: " + dateFormatter.Format(combinedValue) + " " + timeFormatter.Format(combinedValue));
datumtextblock2.Text = ("Combined value: " + dateFormatter.Format(combinedValue2) + " " + timeFormatter.Format(combinedValue2));
System.TimeSpan odecet = combinedValue.Subtract(combinedValue2);
vysledek.Text = odecet.ToString();
}
答案 0 :(得分:0)
您的代码中存在轻微疏忽。获得combinedValue2
后,您应该使用
DateTimeOffset combinedValue2 = new DateTimeOffset(new DateTime(selectedDate2.Year, selectedDate2.Month, selectedDate2.Day) + this.timepicker2.Time);
而不是
DateTimeOffset combinedValue2 = new DateTimeOffset(new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day) + this.timepicker2.Time);
在此之后,您可以使用以下内容来获得您想要的内容。
vysledek.Text = $"{odecet.Days} days, {odecet.Hours} hours, {odecet.Minutes} minutes";
如果您想要始终获得绝对值,可以使用var absoluteOdecet = odecet.Duration();
之类的TimeSpan.Duration
Method。