Hi
How to subtract 2 dates & get No Of Days
Thanks
Hi
How to subtract 2 dates & get No Of Days
Thanks
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
cjard43 reputationPosted Jun 19, 2023, 1:12 AM EDT
Like you would numbers
laterDate - earlierDateThe operation results in a TimeSpan object that describes the period of time between the two dates
For example:
daysBetween will be a double, as the period between the dates could have fractions of a day; the time period between noon on 2nd Jan and midnight in 1st Jan is 1.5 days. If you only want whole days, you can cast to an int, use Math.Floor etc.
Take a look at the other properties of a TimeSpan in the documentation for further ideas on how to work with it
Note, like numbers, if you do earlierDate - laterDate, you'll get a negative TimeSpan
Amit MohantyRank #112 · 20K reputationPosted Jun 19, 2023, 1:23 AM EDT
DateTime startDate = new DateTime(2023, 6, 10); DateTime endDate = new DateTime(2023, 6, 15); TimeSpan duration = endDate.Subtract(startDate); int numberOfDays = duration.Days; Console.WriteLine("Number of days: " + numberOfDays);Raj BhattRank #513 · 4.8K reputationPosted Jun 19, 2023, 1:44 AM EDT
In sql you can do by using DATEDIFF()
SELECT DATEDIFF(day, '2023-06-10', '2023-06-15') AS NumberOfDays;
Vishal YelveRank #178 · 13.6K reputationPosted Jun 19, 2023, 2:48 AM EDT
Hi Ramco,
Try this
using System; public class Program { public static void Main() { var prevDate = new DateTime(2021, 11, 23); //23 Nov 2021 var today = DateTime.Now; //get difference of two dates var diffOfDates = today - prevDate; Console.WriteLine("Difference in Days: {0}", diffOfDates.Days); } }OutPut
Brahma Prakash ShuklaRank #633 · 3.8K reputationPosted Jun 19, 2023, 3:34 AM EDT
DECLARE @StartDate DATE = '2023-06-15';
DECLARE @EndDate DATE = '2023-06-19';
DECLARE @NumberOfDays INT;
SET @NumberOfDays = DATEDIFF(day, @StartDate, @EndDate);
SELECT @NumberOfDays;