2016-11-13 58 views
0

我曾經在波斯日期格式時間戳顯示正確的日期時間,我想轉換爲完全波斯日期,正確本地主機,但如果把它上傳到遠程服務器輸出我的代碼工作改爲公曆日期我如何能在C#

string dt = ""; 
PersianCalendar pc = new PersianCalendar(); 
int Year = Convert.ToInt32(ts.Substring(0, 4)); 
int Month = Convert.ToInt32(ts.Substring(4, 2)); 
int Day = Convert.ToInt32(ts.Substring(6, 2)); 
int Hour = Convert.ToInt32(ts.Substring(8, 2)); 
int Minute = Convert.ToInt32(ts.Substring(10, 2)); 
int Second = Convert.ToInt32(ts.Substring(12, 2)); 

dt = new DateTime(Year, Month, Day, Hour, Minute, Second, 0, pc).ToString("dddd dd MMMM yyyy HH:mm:ss", CultureInfo.CreateSpecificCulture("fa-IR")); 

輸出這個代碼,我期望是(在本地主機):

شنبه22آبان1395 13點43分十秒

和偏遠SER輸出版本

شنبه12نوامبر2016 13點43分十秒

我應該怎麼做它正常工作?

回答

1

DateTime構造函數中的calendar參數用於解釋整數值而不是規定日曆的結果。你寫的代碼是依賴於文化的,這在伊朗並不是一個好的做法,因爲我們的系統中沒有使用正確的文化。我的建議是使用這樣的:

public string GetPersianDateString(DateTime date) 
{ 
    PersianCalendar pc = new PersianCalendar(); 
    string dayOfWeek; 
    switch (pc.GetDayOfWeek(date)) 
    { 
     case DayOfWeek.Sunday: 
      dayOfWeek = "یکشنبه"; 
      break; 
     case DayOfWeek.Monday: 
      dayOfWeek = "دوشنبه"; 
      break; 
     case DayOfWeek.Tuesday: 
      dayOfWeek = "سه شنبه"; 
      break; 
     case DayOfWeek.Wednesday: 
      dayOfWeek = "چهارشنبه"; 
      break; 
     case DayOfWeek.Thursday: 
      dayOfWeek = "پنج شنبه"; 
      break; 
     case DayOfWeek.Friday: 
      dayOfWeek = "جمعه"; 
      break; 
     case DayOfWeek.Saturday: 
      dayOfWeek = "شنبه"; 
      break; 
     default: 
      dayOfWeek = ""; 
      break; 
    } 
    var day = pc.GetDayOfMonth(date).ToString(); 
    string month; 
    switch (pc.GetMonth(date)) 
    { 
     case 1: 
      month = "فروردین"; 
      break; 
     case 2: 
      month = "اردیبهشت"; 
      break; 
     case 3: 
      month = "خرداد"; 
      break; 
     case 4: 
      month = "تیر"; 
      break; 
     case 5: 
      month = "مرداد"; 
      break; 
     case 6: 
      month = "شهریور"; 
      break; 
     case 7: 
      month = "مهر"; 
      break; 
     case 8: 
      month = "آبان"; 
      break; 
     case 9: 
      month = "آذر"; 
      break; 
     case 10: 
      month = "دی"; 
      break; 
     case 11: 
      month = "بهمن"; 
      break; 
     case 12: 
      month = "اسفند"; 
      break; 
     default: 
      month = ""; 
      break; 
    } 
    var year=pc.GetYear(date).ToString(); 
    return dayOfWeek + " " + day + " " + month + " " + year + " " + date.ToShortTimeString(); 
} 

這只是一個草案,你可以寫更好地組織代碼。

+0

它依賴於文化。這是您的Windows設置正確呈現結果而不是代碼。通常其他國家的人根據他們居住的地方選擇文化,法語選擇法語,西班牙語選擇西班牙語,但伊朗人選擇各種各樣的東西。主要是美國英語。 – Emad