2012-05-18 152 views
14

我使用這些代碼來轉換當前日期時間並減去用戶在文本框中鍵入的日期時間。但它在轉換時出現錯誤。如何將Persian Calendar日期字符串轉換爲DateTime?

PersianCalendar p = new System.Globalization.PersianCalendar(); 
       DateTime date = new DateTime(); 
       date = DateTime.Parse(DateTime.Now.ToShortDateString()); 
       int year = p.GetYear(date); 
       int month = p.GetMonth(date); 
       int day = p.GetDayOfMonth(date); 
       string str = string.Format("{0}/{1}/{2}", year, month, day); 
       DateTime d1 = DateTime.Parse(str); 
       DateTime d2 = DateTime.Parse(textBox9.Text); 
       string s = (d2 - d1).ToString().Replace(".00:00:00", ""); 
       textBox10.Text = (d2 - d1).ToString().Replace(".00:00:00",""); 

而從字符串轉換日期時間至今的時間這條線將給予一個錯誤:DateTime d1 = DateTime.Parse(str);

請幫我解決這個問題。

在此先感謝

+1

什麼是你的錯誤? – Tejs

+5

爲什麼要格式化DateTime.Now然後再解析它?爲什麼你給'date'賦值,然後立即給它賦一個不同的值?你爲什麼要將波斯年/月/日解析爲不在波斯日曆中?它*非常*不清楚你想要做什麼,以及波斯日曆適合什麼地方。 –

+0

你不會對'字符串s'做任何事情。 – comecme

回答

6

我解決了這個問題。這是因爲在幾個月內例外,所以如果你想減去兩個彼此的日期時間,你應該將兩者都轉換成公曆,然後你可以減去它們並查看結果。

這裏是代碼:

PersianCalendar p = new PersianCalendar(); 
     string PersianDate1 = textBox1.Text; 
     string[] parts = PersianDate1.Split('/', '-'); 
     DateTime dta1 = p.ToDateTime(Convert.ToInt32(parts[0]), Convert.ToInt32(parts[1]), Convert.ToInt32(parts[2]), 0, 0, 0, 0); 
     string PersianDate2 = textBox2.Text; 
     string[] parts2 = PersianDate2.Split('/', '-'); 
     DateTime dta2 = p.ToDateTime(Convert.ToInt32(parts2[0]), Convert.ToInt32(parts2[1]), Convert.ToInt32(parts2[2]), 0, 0, 0, 0); 
     string s = (dta2 - dta1).ToString().Replace(".00:00:00", ""); 
     textBox3.Text = s; // Show the result into the textbox 
14

不需要在這裏解析日期。

編輯:

本來我只是想指出在OP處理錯誤這個答案。 但我認爲一個完整的答案會更好(儘管延遲:)) 是的,我知道中間日期表示看起來不像波斯日期。但這不是需要的。此代碼使當前的日期和用戶將在日期之間的正常差異

string userInput = "1394/02/31"; 
System.DateTime date = System.DateTime.Today; 
System.Globalization.PersianCalendar p = new System.Globalization.PersianCalendar(); 

int year = p.GetYear(date); 
int month = p.GetMonth(date); 
int day = p.GetDayOfMonth(date); 
System.DateTime currentDate = new System.DateTime(year, month, 1); 
currentDate = currentDate.AddDays(day - 1); 

// validation omitted 
System.String[] userDateParts = userInput.Split(new[] { "/" }, System.StringSplitOptions.None); 
int userYear = int.Parse(userDateParts[0]); 
int userMonth = int.Parse(userDateParts[1]); 
int userDay = int.Parse(userDateParts[2]); 
System.DateTime userDate = new System.DateTime(userYear, userMonth, 1); 
userDate = userDate.AddDays(userDay - 1); 

System.TimeSpan difference = currentDate.Subtract(userDate); 
+0

這仍然是相同的'DateTime d1 = DateTime.Now.Date'。 – comecme

+0

不,它不是:) –

+0

@GrzegorzWilczura它說:年,月和日參數描述了一個不可表示的日期時間。 – aliboy38

10

只需使用上PersianCalendarToDateTime方法:

PersianCalendar p = new PersianCalendar(); 
DateTime now = DateTime.Now; 
DateTime dateT = p.ToDateTime(now.Year, now.Month, now.Day, 0, 0, 0, 0); 

然後讓你的字符串中的格式,只是這樣做:

string str = dateT.ToShortDateString(); 
+2

這種方法從波斯日曆轉換爲我們的日期。所以實際上,你會在遙遠的將來得到一些東西。我懷疑這是他想要的。 –

+0

@GrzegorzWilczura它使用波斯歷來轉換爲我們的一天,這將給你什麼在未來? – mattytommo

+1

因爲今天這段代碼產生2633-08-12 –

5

這裏就是文檔是你的朋友:

PersianCalendar Class

DateTime Constructor (Int32, Int32, Int32, Calendar)

這是確切的代碼你需要:

PersianCalendar p = new System.Globalization.PersianCalendar(); 
DateTime today = DateTime.Today; 
DateTime pDate = new DateTime(p.GetYear(today), p.GetMonth(today), p.GetDayOfMonth(today), p); 
DateTime d2 = DateTime.Parse(textBox9.Text); 
// THIS NEEDS TO BE EXPLAINED 
textBox10.Text = (d2 - pDate).ToString().Replace(".00:00:00",""); 

最後,你想幹什麼?你在textBox10期待的結果是什麼?如果您需要兩個日期之間的天數,那麼只需執行(d2 - pDate).ToString("d"),您將在幾天內獲得差異。也許如果你進一步解釋你想做什麼,而不是你如何去做,我們可以進一步幫助你。

編輯:剛剛意識到什麼comecme說。這將導致該問題的路線是在這裏:

DateTime d2 = DateTime.Parse(textBox9.Text); 

相反,我們需要改變它也使用文化信息,以及:

CultureInfo persianCulture = new CultureInfo("fa-IR"); 
DateTime d2 = DateTime.Parse(textBox9.Text, persianCulture) 

編輯:你是正確的,它只允許以波斯語格式解析日期,但不根據特定的日曆進行驗證。爲了得到這個工作正常,你得手動解析出的日期和實例與PersianCalendar一個新的datetime供貨:

DateTime d2; 
if(Regex.IsMatch(textBox9.Text, "^dddd/dd/dd$")) 
{ 
    d2 = new DateTime(
     int.Parse(textBox9.Substring(0,4)), 
     int.Parse(textBox9.Substring(5, 2)), 
     int.Parse(textBox9.Substring(8, 2)), 
     p); 
} 

你一定要確保輸入您的格式一致肯定指定,否則無法準確解析出DateTime。如果你一個。減去從另一個你會得到一個時間跨度

DateTime today = DateTime.Today; // excludes h/m/s 

    DateTime userdate = DateTime.Parse(textBox9.Text); 

+0

我不認爲你可以從每個可能的波斯日期創建DateTime。波斯第二個月有31天,但公曆不是。所以它會失敗,像'新日期時間(1391,2,31);'。 – comecme

+0

它顯示負數減號結果花花公子 – aliboy38

+0

@comecme:這是有效的,因爲您也提供日曆,這意味着它根據特定日曆驗證日期。 @ aliboy38:當然是的,因爲時間跨度是負的(意思是用戶輸入的日期是在今天的日期之前)。如果用戶提供的日期將小於今天的日期,則逆轉日期時間減法的順序('(pDate-d2).ToString(「d」)')。但是,這又取決於你想要完成什麼。如果你只想要天的一部分(絕對值),那麼只要'Math.Abs​​((pDate - d2).TotalDays)''。 – SPFiredrake

8

您的實際問題似乎在於解析用戶在波斯語calenda中輸入的日期r格式。因此,如果用戶輸入1391/2/31,您希望能夠解析該問題。今天(2012年5月19日)是1391/2/30,所以你最終想要顯示一些像1 day remaining

這個問題有been asked before。然而,接受的答案那裏只是嘗試使用

string persianDate = "1390/02/07"; 
CultureInfo persianCulture = new CultureInfo("fa-IR"); 
DateTime persianDateTime = DateTime.ParseExact(persianDate, 
    "yyyy/MM/dd", persianCulture); 

,不會像1391/2/31日期工作。所以我認爲你必須自己實現解析。

沒有實施任何錯誤檢查,並假設用戶總是使用yyyy/mm/dd,你可以使用以下格式:

// Convert Persian Calendar date to regular DateTime 
var persianDateMatch = System.Text.RegularExpressions.Regex.Match(
    persianTargetTextBox.Text, @"^(\d+)/(\d+)/(\d+)$"); 
var year = int.Parse(persianDateMatch.Groups[1].Value); 
var month = int.Parse(persianDateMatch.Groups[2].Value); 
var day = int.Parse(persianDateMatch.Groups[3].Value); 
var pc = new System.Globalization.PersianCalendar(); 
var target = pc.ToDateTime(year, month, day, 0, 0, 0, 0); 

var difference = target - DateTime.Today; 
differenceLabel.Text = difference.TotalDays.ToString("0"); 

您將需要檢查的正則表達式acually找到任何匹配。您還必須檢查pc.ToDateTime是否不會引發錯誤。不幸的是,波斯日曆似乎沒有像DateTime.TryParse這樣的東西。

無論如何,你不需要今天解析一個波斯日曆,你只需要解析用戶輸入。

儘管文章很舊(2007),您可能也有興趣Farsi Library - Working with Dates, Calendars, and DatePickers

1

下面是我使用的是代碼:

public DateTime ConvertPersianToEnglish(string persianDate) 
     { 
      string[] formats = { "yyyy/MM/dd", "yyyy/M/d", "yyyy/MM/d", "yyyy/M/dd" }; 
      DateTime d1 = DateTime.ParseExact(persianDate, formats, 
               CultureInfo.CurrentCulture, DateTimeStyles.None); 
      PersianCalendar persian_date = new PersianCalendar(); 
      DateTime dt = persian_date.ToDateTime(d1.Year, d1.Month, d1.Day, 0, 0, 0, 0, 0); 
      return dt; 
     } 
1

您還可以使用以下.NET庫使用PersianCalendar那麼容易,因爲日期時間:

Persian Calendar(PersianDateTime) in C#

var persianDateTime = PersianDateTime.Now; 
persianDateTime.EnglishNumber = true; 
Console.Write(persianDateTime.ToString()); 
0

這可以使用Noda Time做到輕鬆了不少:

using System.Globalization; 
using NodaTime; 
using NodaTime.Text; 

... 

CultureInfo culture = CultureInfo.CreateSpecificCulture("fa-IR"); 
CalendarSystem calendar = CalendarSystem.GetPersianCalendar(); 
LocalDate template = new LocalDate(1, 1, 1, calendar); 
LocalDatePattern pattern = LocalDatePattern.Create("yyyy/M/d", culture, template); 
LocalDate result = pattern.Parse("1391/2/30").Value; 

// if you need a DateTime, then: 
DateTime dt = result.AtMidnight().ToDateTimeUnspecified(); 
0

試試這個代碼: 這段代碼編輯者個人意見,「格熱戈日W」的代碼,但他的代碼生成例如錯誤,當用戶輸入日期=「1394/06/31" 和錯誤的‘年,月和日參數描述一個未表示的日期時間’

下面的代碼就可以了:

string userInput = "1394/02/31"; 
System.DateTime date = System.DateTime.Today; 
System.Globalization.PersianCalendar p = new System.Globalization.PersianCalendar(); 

int year = p.GetYear(date); 
int month = p.GetMonth(date); 
int day = p.GetDayOfMonth(date); 
System.DateTime currentDate = new System.DateTime(year, month, day,p); 


System.String[] userDateParts = userInput.Split(new[] { "/" },  System.StringSplitOptions.None); 
int userYear = int.Parse(userDateParts[0]); 
int userMonth = int.Parse(userDateParts[1]); 
int userDay = int.Parse(userDateParts[2]); 
System.DateTime userDate = new System.DateTime(userYear, userMonth, userDay,p); 


System.TimeSpan difference = currentDate.Subtract(userDate); 
相關問題