C# 将日期从波斯语转换为公历

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11222427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:02:27  来源:igfitidea点击:

Convert Date from Persian to Gregorian

c#.netdatetimecalendar

提问by Mahdi Tahsildari

How can I convert Persian date to Gregorian date using System.globalization.PersianCalendar? Please note that I want to convert my Persian Date (e.g. today is 1391/04/07) and get the Gregorian Date result which will be 06/27/2012 in this case. I'm counting seconds for an answer ...

如何使用 System.globalization.PersianCalendar 将波斯日期转换为公历日期?请注意,我想转换我的波斯日期(例如今天是 1391/04/07)并获得公历日期结果,在这种情况下将是 06/27/2012。我在数秒的答案......

采纳答案by Jon Skeet

It's pretty simple actually:

其实很简单:

// I'm assuming that 1391 is the year, 4 is the month and 7 is the day
DateTime dt = new DateTime(1391, 4, 7, persianCalendar);
// Now use DateTime, which is always in the Gregorian calendar

When you call the DateTimeconstructor and pass in a Calendar, it converts it for you - so dt.Yearwould be 2012 in this case. If you want to go the other way, you need to construct the appropriate DateTimethen use Calendar.GetYear(DateTime)etc.

当您调用DateTime构造函数并传入 a 时Calendar,它会为您转换它 -dt.Year在这种情况下是 2012。如果你想走另一条路,你需要构造适当的DateTime然后使用Calendar.GetYear(DateTime)等。

Short but complete program:

简短但完整的程序:

using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        PersianCalendar pc = new PersianCalendar();
        DateTime dt = new DateTime(1391, 4, 7, pc);
        Console.WriteLine(dt.ToString(CultureInfo.InvariantCulture));
    }
}

That prints 06/27/2012 00:00:00.

打印 06/27/2012 00:00:00。

回答by MohammadSoori

You can use this code to convert Persian Date to Gregorian.

您可以使用此代码将波斯日期转换为公历。

// Persian Date
var value = "1396/11/27";
// Convert to Miladi
DateTime dt = DateTime.Parse(value, new CultureInfo("fa-IR"));
// Get Utc Date
var dt_utc = dt.ToUniversalTime();

回答by Fereydoon Barikzehy

I have an extension method for this:

我有一个扩展方法:

 public static DateTime PersianDateStringToDateTime(this string persianDate)
 {
        PersianCalendar pc = new PersianCalendar();

        var persianDateSplitedParts = persianDate.Split('/');
        DateTime dateTime = new DateTime(int.Parse(persianDateSplitedParts[0]), int.Parse(persianDateSplitedParts[1]), int.Parse(persianDateSplitedParts[2]), pc);
        return DateTime.Parse(dateTime.ToString(CultureInfo.CreateSpecificCulture("en-US")));
 }

For more formats and culture-specific formats

有关更多格式和特定​​于文化的格式

Example: Convert 1391/04/07to 06/27/2012

示例:转换1391/04/0706/27/2012