etc./StackOverFlow

두 날짜(일수)의 차이를 계산하시겠습니까?

청렴결백한 만능 재주꾼 2023. 4. 28. 04:05
반응형

질문자 :leora


이 질문은 Java , JavaScriptPHP 에 대해 답변되었지만 C#에는 답변되지 않았습니다. 그렇다면 C#에서 두 날짜 사이의 일 수를 어떻게 계산할 수 있습니까?



StartDateEndDateDateTime 유형이라고 가정합니다.

 (EndDate - StartDate).TotalDays

Greg Beech

맨 위의 대답은 정확하지만 전체 일을 int로 원하고 날짜의 시간 구성 요소를 기꺼이 잊어 버리려면 다음을 고려하십시오.

 (EndDate.Date - StartDate.Date).Days

StartDateEndDateDateTime 유형이라고 가정합니다.


Darren

날짜 빼기 결과인 TimeSpan 개체를 사용합니다.

 DateTime d1; DateTime d2; return (d1 - d2).TotalDays;

Vitaliy Liptchinsky

나는 이것이 당신이 원하는 것을 할 것이라고 생각합니다.

 DateTime d1 = DateTime.Now; DateTime d2 = DateTime.Now.AddDays(-1); TimeSpan t = d1 - d2; double NrOfDays = t.TotalDays;

pyrocumulus

DateTime xmas = new DateTime(2009, 12, 25); double daysUntilChristmas = xmas.Subtract(DateTime.Today).TotalDays;

Philip Wallace

누군가가 전체 일 수를 두 배( DateTime 유형의 a , b )로 원하는 경우:

 (a.Date - b.Date).TotalDays

kingPuppy

// Difference in days, hours, and minutes. TimeSpan ts = EndDate - StartDate; // Difference in days. int differenceInDays = ts.Days; // This is in int double differenceInDays= ts.TotalDays; // This is in double // Difference in Hours. int differenceInHours = ts.Hours; // This is in int double differenceInHours= ts.TotalHours; // This is in double // Difference in Minutes. int differenceInMinutes = ts.Minutes; // This is in int double differenceInMinutes= ts.TotalMinutes; // This is in double

초, 밀리초 및 틱 단위로 차이를 얻을 수도 있습니다.


Vijay Maheriya

당신은 이것을 시도 할 수 있습니다

 EndDate.Date.Subtract(DateTime.Now.Date).Days

Rohidas Kadam

두 날짜 사이의 날짜를 계산할 때 종종 시간(시간)에 대한 논쟁이 있습니다. 질문에 대한 답변과 댓글도 예외는 아닙니다.

성능이 문제가 되지 않는다면 중간 변환을 통해 계산을 문서화하는 것이 좋습니다. 예를 들어 (EndDate - StartDate).Days StartDateEndDate 의 시간 구성 요소에 따라 달라지기 때문에 직관적이지 않습니다.

  • 기간(일)에 일의 분수를 포함하려면 이미 제안된 대로 (EndDate - StartDate).TotalDays .
  • 기간이 이틀 사이의 거리를 반영하도록 하려면 (EndDate.Date - StartDate.Date).Days
  • 기간이 시작 날짜의 아침과 종료 날짜의 저녁 사이의 기간을 반영하도록 하려면(일반적으로 프로젝트 관리 소프트웨어에 표시됨) (EndDate.Date - StartDate.Date).Days + 1

Ama

시간 범위를 사용하면 많은 속성이 있으므로 문제를 해결할 수 있습니다.

 DateTime strt_date = DateTime.Now; DateTime end_date = Convert.ToDateTime("10/1/2017 23:59:59"); //DateTime add_days = end_date.AddDays(1); TimeSpan nod = (end_date - strt_date); Console.WriteLine(strt_date + "" + end_date + "" + "" + nod.TotalHours + ""); Console.ReadKey();

Vijay Vj

용 와 a b 두 같은 DateTime 유형 :

 DateTime d = DateTime.Now; DateTime c = DateTime.Now; c = d.AddDays(145); string cc; Console.WriteLine(d); Console.WriteLine(c); var t = (c - d).Days; Console.WriteLine(t); cc = Console.ReadLine();

Pratyush Dhanuka

나와 같은 초보자를 위해 샘플을 int 로 변환하는 간단한 줄에서 이 작은 문제에 걸려 넘어질 것입니다.

 int totalDays = Convert.ToInt32((DateTime.UtcNow.Date - myDateTime.Date).TotalDays);

오늘(DateTime.UtcNow.Date)부터 원하는 날짜(myDateTime.Date)까지의 총 일수를 계산합니다.

myDateTime이 어제이거나 오늘보다 오래된 날짜이면 양수(+) 정수 결과를 제공합니다.

반면에 myDateTime이 내일 또는 미래 날짜인 경우 더하기 규칙으로 인해 음수(-) 정수 결과를 제공합니다.

즐거운 코딩! ^_^


Curbside Coder

먼저 나중에 반환할 클래스를 선언합니다.

 public void date() { Datetime startdate; Datetime enddate; Timespan remaindate; startdate = DateTime.Parse(txtstartdate.Text).Date; enddate = DateTime.Parse(txtenddate.Text).Date; remaindate = enddate - startdate; if (remaindate != null) { lblmsg.Text = "you have left with " + remaindate.TotalDays + "days."; } else { lblmsg.Text = "correct your code again."; } } protected void btncal_Click(object sender, EventArgs e) { date(); }

버튼 컨트롤을 사용하여 위의 클래스를 호출합니다. 다음은 예입니다.


Muba

아래 코드를 사용할 수 있습니다.

 int DateDifInSecond = EndDate.Subtract(StartDate).TotalSeconds

Code_Worm

두 날짜의 차이를 얻은 다음 다음에서 날짜를 가져옵니다.

 int total_days = (EndDate - StartDate).TotalDays

Muhamad Eissa

protected void Calendar1_SelectionChanged(object sender, EventArgs e) { DateTime d = Calendar1.SelectedDate; // int a; TextBox2.Text = d.ToShortDateString(); string s = Convert.ToDateTime(TextBox2.Text).ToShortDateString(); string s1 = Convert.ToDateTime(Label7.Text).ToShortDateString(); DateTime dt = Convert.ToDateTime(s).Date; DateTime dt1 = Convert.ToDateTime(s1).Date; if (dt <= dt1) { Response.Write("<script>alert(' Not a valid Date to extend warranty')</script>"); } else { string diff = dt.Subtract(dt1).ToString(); Response.Write(diff); Label18.Text = diff; Session["diff"] = Label18.Text; } }

sangeetha

출처 : http:www.stackoverflow.com/questions/1607336/calculate-difference-between-two-dates-number-of-days

반응형