어떻게 변환하는 페르시아어 일정 날짜 문자열을 DateTime?

StackOverflow https://stackoverflow.com//questions/10655116

  •  11-12-2019
  •  | 
  •  

문제

내가 사용하는 이러한 코드를 변환하기 위한 현재 날짜 및 마이너스 그 날짜와 시간에는 사용자의 유형에 textbox.하지만 그것은 오류로 변환하는 동안.

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 문자열에서 날짜 시간:DateTime d1 = DateTime.Parse(str);

나를 도와주세이 문제를 해결합니다.

사전에 감사합니다

도움이 되었습니까?

해결책 4

나는 그 문제를 해결했습니다.몇 개월 만에 예외로 인해 있었기 때문에 서로 마이너스를 뺀 두 시간을 마이너스로 빼내려면 그로고리어 캘린더를 모두 빼고 결과를 볼 수 있습니다.

여기에 코드가 있습니다 :

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 
.

다른 팁

여기서 날짜를 파싱 할 필요가 없습니다.

편집 :

원래이 답변으로 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);
.

ToDateTime 클래스의 PersianCalendar 메소드를 사용하십시오.

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();
.

당신은 실제 문제에 거짓말을 보인 분석 날짜를 사용자 입력에 페르시아어 일정 형식입니다.경우에 따라서,사용자 입력 1391/2/31 할 수 있을 분석하다.오늘(월 19 2012) 1391/2/30 그래서 당신이 마지막으로 표시하고 싶은 뭔가 1 day remaining.

이 질문은 .그러나,허용된 응답이 사용하려고 시도

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");

당신이 필요한지 확인하려면 regex 요금이 불포함되어 발견되는 모든 일치합니다.당신은 또한 확인하려면 pc.ToDateTime 도 한 가지 오류가 있습니다.불행하게도,이 존재하지 않도 DateTime.TryParse 위한 페르시아어 일정입니다.

어쨌든,당신은 필요하지 않 분석으로 오늘 페르시아,당신은 단지 구문 분석하는 사용자 입력이 있습니다.

당신은 또한에 관심이있을 수 있습니다 페르시아어 라이브러리-노동으로 날짜를,캘린더,및 여러분의 모든 계산을 기억, 도 기사는 매우 늙은(2007).

여기서 문서가 귀하의 친구 인 경우 :

PersianCalendar 클래스

DateTime 생성자 (Int32, Int32, Int32, 캘린더) / P>

이 필요가 필요한 정확한 코드입니다.

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)
.

편집 : 올바르게, 페르시아 형식의 날짜를 구문 분석 할 수 있지만 특정 캘린더에 따라 유효성을 검사하지 않습니다. 이 작업을 올바르게 가져 오려면 Date를 수동으로 구문 분석하고 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);
.

다른 쪽에서 하나를 기분 맞으면 시간대를 얻습니다.

  TimeSpan diff = today - userDate;
.

이 시간 스팬의 속성을 사용하여 원하는대로 표시 할 수 있습니다.

변환 양식 / 페르시아어 달력을 관리하려면 여기에 좋은 해결책이 있습니다 :

.NET 페르시아어 (Jalali Calendar)의 날짜 문자열을 DateTime 객체로 파싱하는 방법은 무엇입니까?

참조 :

datetime.today

Timespan

여기에있는 코드가 있습니다 :

  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;
        }
.

"NOFOLLOW"> NEDA 시간 : 를 사용하여 훨씬 쉬워 질 수 있습니다.

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();
.

다음 .NET 라이브러리를 사용하여 persiancalendar를 datetime처럼 쉽게 사용할 수 있습니다.

페르시아어 캘린더 (PersiAndatime)

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

이 코드를 사용해보십시오. 이 코드는 "Grzegorz W"가 게시 한 코드가 편집되었지만 사용자 입력 날짜="1394/06/31"및 오류가 "해, 월 및 일] 매개 변수"un-un-dateTime "

코드 아래가 괜찮습니다 :

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);
.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top