C# 格式化 TimeSpan 以显示日期
C# Formatting TimeSpan to show a date
我正在开发一个简单的程序来计算会员的年龄并根据年龄应用正确的会员费。
public static DateTime DateTime()
{
DateTime birth = new System.DateTime(1991, 9, 20);
DateTime today = new System.DateTime(2017, 1, 22);
TimeSpan age = today - birth;
Console.WriteLine(age);
return birth;
}
这是我正在使用的代码,我的 return 值为
9256.00:00:00
如何将其解析为更易读的 yyyy,mm,dd 格式?
正如Jon Skeet所说:
TimeSpan has no sensible concept of "years" because it depends on the
start and end point.
你为什么不试试他的 Noda Time 呢?
您可以手动下载here
也可以除以365.25(一年的平均天数),得到整数
Convert.ToInt32(age.Days / 365.25);
使用nodatime
var ld1 = new LocalDate(1991, 9, 20);
var ld2 = new LocalDate(2017, 1, 22);
var period = Period.Between(ld1, ld2);
Debug.WriteLine(period.Years);
Debug.WriteLine(period.Months);
Debug.WriteLine(period.Days);
我正在开发一个简单的程序来计算会员的年龄并根据年龄应用正确的会员费。
public static DateTime DateTime()
{
DateTime birth = new System.DateTime(1991, 9, 20);
DateTime today = new System.DateTime(2017, 1, 22);
TimeSpan age = today - birth;
Console.WriteLine(age);
return birth;
}
这是我正在使用的代码,我的 return 值为
9256.00:00:00
如何将其解析为更易读的 yyyy,mm,dd 格式?
正如Jon Skeet所说:
TimeSpan has no sensible concept of "years" because it depends on the start and end point.
你为什么不试试他的 Noda Time 呢?
您可以手动下载here
也可以除以365.25(一年的平均天数),得到整数
Convert.ToInt32(age.Days / 365.25);
使用nodatime
var ld1 = new LocalDate(1991, 9, 20);
var ld2 = new LocalDate(2017, 1, 22);
var period = Period.Between(ld1, ld2);
Debug.WriteLine(period.Years);
Debug.WriteLine(period.Months);
Debug.WriteLine(period.Days);