Datetime substraction from DateTime value in c# - c#

How to subtract "year=117 month=1 day=28 hour=7 min=43 sec=10" from a DateTime in c#?
I have already tried like below
split the string using regex.
add each item with -ve sign to a current DateTime value.
But I think it's not an efficient way.
Can anyone help me?

You can use below Code as per you requirement to get desired Result. Replace your Date, Time, year values in "new System.DateTime(1996, 6, 3, 22, 15, 0);"
System.DateTime date1 = new System.DateTime(1996, 6, 3, 22, 15, 0);
System.DateTime date2 = new System.DateTime(1996, 12, 6, 13, 2, 0);
System.DateTime date3 = new System.DateTime(1996, 10, 12, 8, 42, 0);
// diff1 gets 185 days, 14 hours, and 47 minutes.
System.TimeSpan diff1 = date2.Subtract(date1);
// date4 gets 4/9/1996 5:55:00 PM.
System.DateTime date4 = date3.Subtract(diff1);
// diff2 gets 55 days 4 hours and 20 minutes.
System.TimeSpan diff2 = date2 - date3;
// date5 gets 4/9/1996 5:55:00 PM.
System.DateTime date5 = date1 - diff2;

you can try DateTime's subtraction.
for that first you have to make valid DateTime object from your information and then subtract that date from current date.
see below code,
int year = 117, month = 01, day = 28;
int hour = 07, minute = 43, second = 10;
DateTime timeToSubtract =
new DateTime(year > 0? year : 1, month > 0 ? month : 1, day > 0 ? day : 1, hour, minute, second);
DateTime subtractedDate =
new DateTime((DateTime.Now - timeToSubtract).Ticks);
as you can see, we are creating a date time object with information we have (date and time which should be subtracted form current date time) by, new DateTime(year, month, day, hour, minute, second) and then subtracting this from DateTime.Now, and then creating final date out of result of this subtraction.
here in last line we are creating a date (of past). this date is of specified time ago.

Related

From total hours amount how to determine Date and Month

Format is DD/MM/YYYY. And for example I will have an int number like 240. This number is total hours actually. Lets accept "01/01/2023 01:00" as a first hour(total hour 1) and "02/01/2023 01:00" as a 25. hour(total hour 24+1=25) from the year beginning. So what would be the date for 240.hours totally? In that case it should be formatted like 11/01/2023 01:00 but I couldn't figure out how to format that.
Your question is a little confusing; I wasn't sure about what you were after, although I think I got it after reading the comments.
Try running this code; I think it will be a help to you.
using System;
DateTime d = DateTime.Now;
var lastMonth = d.AddMonths(-1);
var nextMonth = d.AddMonths(1);
var yesterday = d.AddDays(-1);
var tomorrow = d.AddDays(1);
// lod = length of day
TimeSpan lod1 = new TimeSpan(days: 1, hours: 0, minutes: 0, seconds: 0);
TimeSpan lod2 = new TimeSpan(days: 0, hours: 23, minutes: 59, seconds: 59, milliseconds: 1_000);
if (lod1 != lod2)
{
Console.WriteLine($"This lne should not be seen; {nameof(lod1)}");
}
var tomorrow2 = d.AddDays(lod1.Days);
if (tomorrow != tomorrow2)
{
Console.WriteLine($"This lne should not be seen; {nameof(tomorrow)}");
}
Console.WriteLine($"Tomorrow lives in the month of {tomorrow.Month} and will be day {tomorrow.Day} of that month.\n");
var periodOfTime = new TimeSpan(tomorrow.EndOfDay().Ticks - yesterday.StartOfDay().Ticks);
Console.WriteLine($"{periodOfTime.Days} days between yesterday and tomorrow.");
Console.WriteLine($"{periodOfTime.TotalDays} total days between yesterday and tomorrow.");
var someFutureDate = yesterday.AddDays(periodOfTime.Days);
var someFutureDate2 = yesterday.AddDays(periodOfTime.TotalDays);
Console.WriteLine();
Console.WriteLine($"1) Two {nameof(periodOfTime.Days)} after yesterday is:");
Console.WriteLine(someFutureDate.ToString("yyyy-MM-dd HH:mm:ss.fffff"));
Console.WriteLine(someFutureDate.DayOfWeek);
Console.WriteLine();
Console.WriteLine($"2) Two {nameof(periodOfTime.TotalDays)} after yesterday is:");
Console.WriteLine(someFutureDate2.ToString("yyyy-MM-dd HH:mm:ss.fffff"));
Console.WriteLine(someFutureDate2.DayOfWeek);
internal static class Extensions
{
public static DateTime StartOfDay(this DateTime date) =>
new(date.Year, date.Month, date.Day, 0, 0, 0, 0, date.Kind);
public static DateTime EndOfDay(this DateTime date) =>
new(date.Year, date.Month, date.Day, 23, 59, 59, 999, date.Kind);
}
Running this now, I get:
Tomorrow lives in the month of 12 and will be day 6 of that month.
2 days between yesterday and tomorrow.
2.999999988425926 total days between yesterday and tomorrow.
1) Two Days after yesterday is:
2022-12-06 17:05:52.55833
Tuesday
2) Two TotalDays after yesterday is:
2022-12-07 17:05:52.55733
Wednesday

Adding the difference of two dates to another date, avoiding leap year

My goal is to figure out the difference between two dates and then add that amount of days to the original start.
DateTime originalStart = new DateTime(2015, 1, 1);
DateTime newDate = originalStart.AddDays((endDate - startDate).TotalDays);
For example with the following params:
original start: 1/1/2015
start date: 1/1/2016
end date: 1/1/2017
newDate should be: 1/1/2016 (difference between start and end is 1 year so then we add that one year to original start)
My problem is that if a leap year is part of the date difference between endDate and startDate and then I go and add those days to originalStart. I end up with dates like 1/2/2016 for newDate.
Any idea how I can avoid leap years here to make sure if the difference between 1/1/2016 and 1/1/2017 is rounded. I would only like to add exactly one year to originalStart and not the extra day because of the leap year.
DateTime originalStart = new DateTime(2015, 1, 1);
DateTime zeroTime = new DateTime(1, 1, 1);
DateTime endDate = new DateTime(2016, 1,1);
endDate .Dump();
DateTime startDate= new DateTime(2017, 1,1);
startDate.Dump();
TimeSpan span = startDate- endDate ;
// because we start at year 1 for the Gregorian
// calendar, we must subtract a year here.
int years = (zeroTime + span).Year - 1;
int months = (zeroTime + span).Month - 1;
int days = (zeroTime + span).Day;
years.Dump();
months.Dump();
days.Dump();
originalStart= originalStart.AddMonths(months);
originalStart = originalStart.AddYears(years);
originalStart = originalStart.AddDays(days);

DateTime go to first occurrence of hour/minute/second

Given this datetime of January 1 2015 at 23:00 hours:
var someDate = new DateTime(2015, 1, 1, 23, 0, 0);
And given the int 6, which is the desired hour, how do I return the first following datetime where the hour is 6? In this case, someDate and 6 would return a new DateTime of January 2 2015 at 06:00 hours.
I would simply add the hours to the original date and add another day if the result is before the original time:
var someDate = new DateTime(2015, 1, 1, 23, 0, 0);
var result = someDate.Date.AddHours(6); // note the "Date" part
if (result < someDate) result = result.AddDays(1);
You just have to add one day to the date and six hours to the result:
var someDate = new DateTime(2015, 1, 1, 23, 0, 0);
var result = someDate.Date.AddDays(1).AddHours(6);
Note the use of Date property - it will give you the start od the day and from there it's easy to navigate forward.
Try this:
while(someDate.Hour != 6){
someDate = someDate.AddHours(1);
}
Assuming you meant 24h clock, you can try this:
public DateTime GetDate(DateTime someDate,int hour)
{
return someDate.Hour>=hour? someDate.Date.AddDays(1).AddHours(6):someDate.Date.AddHours(6);
}
Something like this should do it:
public DateTime FollowingHour(DateTime start, int hour)
{
DateTime atHour = start.Date.AddHours(6);
if(atHour < start)
{
atHour += TimeSpan.FromDays(1);
}
return atHour;
}

How to work with DateTime.Now to ticks [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to add the phones current time to my date time list. I need it to be able to subtract with the ticks. I have tried using phonecurrentime.ToString("dd hh:mm"); but because it's a string there are no ticks and all sorts of errors!
I need it to work with DateTime.now.
Here is my code:
InitializeComponent();
List<DateTime> theDates = new List<DateTime>();
DateTime fileDate, closestDate;
theDates.Add(new DateTime(2000, 1, 1, 10, 29, 0));
theDates.Add(new DateTime(2000, 1, 1, 3, 29, 0));
theDates.Add(new DateTime(2000, 1, 1, 3, 29, 0));
// This is the date that should be found
theDates.Add(new DateTime(2000, 1, 1, 4, 22, 0));
// This is the date you want to find the closest one to
fileDate = DateTime.Now;
long min = long.MaxValue;
foreach (DateTime date in theDates)
{
if (Math.Abs(date.Ticks - fileDate.Ticks) < min)
{
min = Math.Abs(date.Ticks - fileDate.Ticks);
closestDate = date;
}
}
Darren Davies above is correct.
You can add/subtract datetime objects. The result is of type TimeSpan, which lets you easily compare date and/or time differences.
Also, you should give a name to each date you add to your list (assign to a variable then add to list). A month later you won't remember what each day meant ;)
if you have a string and want to convert it to DateTime you can use
CultureInfo cf = new CultureInfo("en-us");
if(DateTime.TryParseExact("12 12:45", "dd hh:mm", cf, DateTimeStyles.None, out fileDate))
{
// your code
}
and your code would look like:
List<DateTime> theDates = new List<DateTime>();
DateTime fileDate, closestDate;
theDates.Add(new DateTime(2000, 1, 1, 10, 29, 0));
theDates.Add(new DateTime(2000, 1, 1, 3, 29, 0));
theDates.Add(new DateTime(2000, 1, 1, 3, 29, 0));
// This is the date that should be found
theDates.Add(new DateTime(2000, 1, 1, 4, 22, 0));
CultureInfo cf = new CultureInfo("en-us");
string timeToParse = phonecurrentime.ToString("dd hh:mm");
if(DateTime.TryParseExact(timeToParse, "dd hh:mm", cf, DateTimeStyles.None, out fileDate))
{
long min = long.MaxValue;
foreach (DateTime date in theDates)
{
if (Math.Abs(date.Ticks - fileDate.Ticks) < min)
{
min = Math.Abs(date.Ticks - fileDate.Ticks);
closestDate = date;
}
}
}
if you want to compare the time part of the dateTime you can use TimeOfDay property:
TimeSpan ts = DateTime.Now.TimeOfDay;
foreach (DateTime date in theDates)
{
long diff = Math.Abs(ts.Ticks - date.TimeOfDay.Ticks);
if (diff < min)
{
min = diff;
closestDate = date;
}
}
fileDate = phonecurrentime.ToString("dd hh:mm");
Will not compile. fileDate is a DateTime object. You need to assign it to another DateTime object, not a string.
If phonecurrenttime is a DateTime you can ommit the .ToString() method.
fileDate = phonecurrenttime;
Edit
From your comment, if you simply want to assign the current ddate/time to fileDate you can use DateTime.Now:
fileDate = DateTime.Now;

C# seconds since specific date

In C# 3.0, how do I get the seconds since 1/1/2010?
Goes like this:
TimeSpan test = DateTime.Now - new DateTime(2010, 01, 01);
MessageBox.Show(test.TotalSeconds.ToString());
For one liner fun:
MessageBox.Show((DateTime.Now - new DateTime(2010, 01, 01))
.TotalSeconds.ToString());
You can substract 2 DateTime instances and get a TimeSpan:
DateTime date = new DateTime(2010,1,1);
TimeSpan diff = DateTime.Now - date;
double seconds = diff.TotalSeconds;
Just to avoid timezone issues
TimeSpan t = (DateTime.UtcNow - new DateTime(2010, 1, 1));
int timestamp = (int) t.TotalSeconds;
Console.WriteLine (timestamp);
It's really a matter of whose 2010-Jan-01 you're using and whether or not you wish to account for daylight savings.
//I'm currently in Central Daylight Time (Houston, Texas)
DateTime jan1 = new DateTime(2010, 1, 1);
//days since Jan1 + time since midnight
TimeSpan differenceWithDaylightSavings = DateTime.Now - jan1;
//one hour less than above (we "skipped" those 60 minutes about a month ago)
TimeSpan differenceWithoutDaylightSavings = (DateTime.UtcNow - jan1.ToUniversalTime());
//difference for those using UTC and 2010-Jan-01 12:00:00 AM UTC as their starting point
// (today it's 5 hours longer than differenceWithDaylightSavings)
TimeSpan utcDifference = (DateTime.UtcNow - new DateTime(2010, 1, 1));
Difference with Daylight Savings: 105.15:44:09.7003571
Difference without Daylight Savings: 105.14:44:09.7003571
UTC Difference: 105.20:44:09.7003571
To get the seconds, use the TotalSeconds property off the TimeSpan object.
protected void Page_Load(object sender, EventArgs e)
{
SecondsSinceNow(new DateTime(2010, 1, 1, 0, 0, 0));
}
private double SecondsSinceNow(DateTime compareDate)
{
System.TimeSpan timeDifference = DateTime.Now.Subtract(compareDate);
return timeDifference.TotalSeconds;
}
DateTime t1 = DateTime.Now;
DateTime p = new DateTime(2010, 1, 1);
TimeSpan d = t1 - p;
long s = (long)d.TotalSeconds;
MessageBox.Show(s.ToString());

Categories