通用Windows平台(UWP)DateTime似乎不支持DateTime(link)的这个构造函数。
DateTime构造函数(Int32,Int32,Int32,日历)
我正在编写的应用程序的核心功能是在不同的日历格式(例如gregorian,hijri,希伯来语)之间转换DateTimes,之前我依靠该构造函数来执行转换。
知道如何在通用应用程序上执行日期转换,因为这个ctor丢失了吗?例如将Hijri /希伯来日期转换为Greogiran?
-Tariq
答案 0 :(得分:1)
如果要使用.NET类,这些是ToDateTime类中的Calendar方法,用于将该日历中的日期转换为DateTime(Gregorian):
int persianYear = 1394;
int persianMonth = 8;
int persianDay = 10;
var persianCalendar = new System.Globalization.PersianCalendar();
DateTime gregDateTime = persianCalendar.ToDateTime(persianYear, persianMonth, persianDay, 0, 0, 0, 0);
Debug.WriteLine(
string.Format(
"{0}/{1}/{2} in persian is {3}/{4}/{5} in gregorian",
persianYear,
persianMonth,
persianDay,
gregDateTime.Year,
gregDateTime.Month,
gregDateTime.Day
));
输出:
波斯语中的1394/8/10是gregorian的2015/11/1
还有GetYear,GetMonth和类似的方法可以转换回来。
但是如果您想使用Windows运行时类(推荐),Calendar类可以通过ChangeCalendarSystem方法进行转换。您可以使用年,月和日属性来获取和设置日期组件。
以下是一个示例转换方法,它将日历组件从日历系统转换为另一个:
private void ConvertDate(
string from,
int year,
int month,
int day,
string to,
out int convertedYear,
out int convertedMonth,
out int convertedDay) {
Calendar calendar = new Calendar();
calendar.ChangeCalendarSystem(from);
calendar.Year = year;
calendar.Month = month;
calendar.Day = day;
calendar.ChangeCalendarSystem(to);
convertedYear = calendar.Year;
convertedMonth = calendar.Month;
convertedDay = calendar.Day;
}
使用该方法将波斯语转换为Hijri和Hijri为Gregorian的示例:
int persianYear = 1394;
int persianMonth = 8;
int persianDay = 10;
int hijriYear;
int hijriMonth;
int hijriDay;
ConvertDate(
CalendarIdentifiers.Persian,
persianYear,
persianMonth,
persianDay,
CalendarIdentifiers.Hijri,
out hijriYear,
out hijriMonth,
out hijriDay);
Debug.WriteLine(
string.Format(
"{0}/{1}/{2} in Persian is {3}/{4}/{5} in Hijri",
persianYear,
persianMonth,
persianDay,
hijriYear,
hijriMonth,
hijriDay
));
int gregYear;
int gregMonth;
int gregDay;
ConvertDate(
CalendarIdentifiers.Hijri,
hijriYear,
hijriMonth,
hijriDay,
CalendarIdentifiers.Gregorian,
out gregYear,
out gregMonth,
out gregDay);
Debug.WriteLine(
string.Format(
"{0}/{1}/{2} in Hijri is {3}-{4}-{5} in Gregorian",
hijriYear,
hijriMonth,
hijriDay,
gregYear,
gregMonth,
gregDay
));
输出:
1394/8/10波斯语是Hijri的1437/1/19
在Hijri的1437/1/19是格里高利的2015/11/1