Round up DateTime - c#

For my SteamBot I want to store the date and the time when the item is tradable again.
Example:
// DateNow = 05.06.2019 13:37:00
(+ 7 days due to Steam's trade policy)
// DateNow+7Days = 12.06.2019 13:37:00
// DateIneed = 13.06.2019 09:00:00
So the DateTime I need is CurrentDateTime + 7 Days + The rest to 9 o'clock
This is how far I come:
var date = DateTime.Now.AddDays(7);
Is there any smart way to always get the DateTime I need?
Language is C#

You can check if it is before 9 o'clock today, then set the time to 9, else add one day and set the time to 9, should be fairly easy I think.
var time = DateTime.Now;
var date = time.Hour <= 9
? time.Date.AddDays(7).AddHours(9)
: time.Date.AddDays(7).AddHours(9).AddDays(1);

The DateTime.Date field exposes just the date of a DateTime, you can then add an arbitrary TimeSpan to that to set the time of a DateTime object to whatever you want;
DateTime.Now.AddDays(7).Date.Add(new TimeSpan(9, 0, 0))
Check it out in action here: https://dotnetfiddle.net/l3X37y
Given the hour of the day may be past 9AM already, it's possible to end up with a DateTime less than 7 days, to counter this you can check if the hour of the day exceeds what you're going to set the DateTime to and add a day if it does, like so;
DateTime dt = DateTime.Now.AddDays(7);
dt = dt.Date.Add(new TimeSpan(dt.Hour >= 9 ? 1 : 0, 9, 0, 0))
See this one in action here: https://dotnetfiddle.net/lfVGis

Related

Add day to dateTime [duplicate]

This question already has answers here:
Why DateTime.AddHours doesn't seem to work?
(8 answers)
Closed 6 years ago.
I have dateTime variable and I would like to add one day if date is not the last day of month, but one day before the last.
endDate = newDate(2016, 8, 30);//create date for test
if (DateTime.DaysInMonth(endDate.Year, endDate.Month) == (int)31 && endDate.Day == (int)30)
endDate.AddDays(1);
From debugger I can see that execution goes on endDate.AddDays(1); but endDate is still the same (30.08.2016) as if AddDays function doesn't work.
Anybody knows why?
AddDays does not change the date but returns a new date with the added days. So for endDate to change you must assign the output of the function to it:
var endDate = new DateTime(2016, 8, 30);
endDate = endDate.AddDays(1);
It returns a result that you have to assign as a DateTime is a struct and is immutable. Also if you checked out the documentation you will see that the method returns a DateTime instance.
endDate = endDate.AddDays(1);
About your logic, you want to increment it by 1 date if its the day before the last day of the month. What you have now is wrong and could be better written like this:
// only increment if one day before last day of month
if ((DateTime.DaysInMonth(endDate.Year, endDate.Month) - 1) == endDate.Day)
endDate = endDate.AddDays(1); // assign the returned value
Take the result from the last day and subtract 1 to get the day before the last day of the month. If that is equal to your date's current day of the month then increment by one.
Not all months have 31 days.
Here's the updated piece of code:
var endDate = new DateTime(2017, 2, 27);//create date for test
var daysInMonth = DateTime.DaysInMonth(endDate.Year, endDate.Month);
if(endDate.Day == daysInMonth - 1)
endDate = endDate.AddDays(1);

Get week number for different startdate

I can get week number if I use normal way like that. As you know this one calculates week number according to normal start date which is 01.01.2015.
CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(mydate, CultureInfo.CurrentCulture.DateTimeFormat.CalendarWeekRule, CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek)
But I want to change that start date. For instance my first week of year will be 01.07.2015 and according to that date I want to calculate week of year for given date.
Substract a difference between new year and your start date from the mydate object
var startDate = new DateTime(2015, 7, 1);
var newYear = new DateTime(2015, 1, 1);
var culture = CultureInfo.CurrentCulture;
var weekOfYear = culture.Calendar.GetWeekOfYear(
mydate.Add(newYear - startDate),
culture.DateTimeFormat.CalendarWeekRule,
culture.DateTimeFormat.FirstDayOfWeek);
Maybe you could calculate the week number for your start date (e.g 01.07.2015 - 27) and then what is the week number for the actual date - e.g 12.12.2015 (50), and then just subtract - in this case 23?
Just subtract the number of days between your wished week-1 date and the default start date and use that offset each time you calculate (.AddDays(offset)).
That way :
DateTime startDateTime = new DateTime(2015,07,01) ;
int fisrtDayOfWeek = 0 ; // 0:sunday for US, 1:Monday for many other coutries
DateTime week1StartDateTime = startDateTime ;
for (int i=1;i<6;i++) if ((int)startDateTime.AddDays(i).Day==fisrtDayOfWeek )
week1StartDateTime = startDateTime.AddDays(i) ;
int weekNumber= mydate<week1StartDateTime ? 1 :
((int)(mydate-week1StartDateTime).TotalDays)/7+1 ;
// note : casting double to int provides the floor (not round)

Calculate the annual use of a service starting from the date of signing

I need to calculate the annual use of a service starting from the date of signing. Something like:
select Count(*) from TABLENAME where Date >= MYDATE
MYDATE need to be calculate from a subscription date and I need to get the last year date from subscription referring to the current date
Some examples:
subscription date: 2007-06-29
if current date is : 2015-04-29 then date is: 2014-06-29
if current date is : 2015-06-29 then date is: 2015-06-29
if current date is : 2015-06-29 then date is: 2015-06-29
I'm using c# to calculate the date but it crashes in leapyear:
var date = new DateTime(DateTime.Now.Year, subscriptionDate.Month, subscriptionDate.Day);
if (DateTime.Now.Date < date)
{
date = date.AddYears(-1);
}
I was wondering if there were a clever/better way to do it in c# or mysql also handling leapyear
---UPDATE----
Running example with suggested solutions
Well, I'd do it in Noda Time, myself:
LocalDate subscriptionDate = ...;
LocalDate today = ...; // Need to take time zone into account
int years = Period.Between(subscriptionDate, today);
return subscription.PlusYears(years);
With .NET that would be slightly harder, but I'd still go for the approach of adding years (and letting it do the truncation for Feb 29th):
// Only call this *once* - otherwise you could get inconsistent results
DateTime today = DateTime.Today;
int years = today.Year - subscriptionDate.Year;
DateTime candidate = subscriptionDate.AddYears(years);
// We might have overshot, in which case lower the number of years.
return candidate <= today ? candidate : subscriptionDate.AddYears(years - 1);
Thanks to Yuri Dorokhov answer and Jon Skeet suggestion
I found a solution that works well and handle leap year:
int year = DateTime.Now.DayOfYear >= subscriptionDate.DayOfYear ?
DateTime.Now.Year : DateTime.Now.Year - 1;
var date = new DateTime(year, 1, 1).AddDays(subscriptionDate.DayOfYear - 1);
--------UPDATE------
I leave here this answer as reference but it does not handle well leap year so don't use it
Use mysql DATE_SUB function
DATE_SUB(Date, INTERVAL 1 YEAR)

Calculate minutes from a certain time to current time c# [duplicate]

This question already has answers here:
What is the easiest way to subtract time in C#?
(7 answers)
Closed 8 years ago.
I have a certain time ie. 10.30 AM. The user makes entry in a table. If the user makes entry after 10.30 AM , then the number of minutes from 10.30 Am to the current time should be calculated and set to a string.
Here is what I tried uptil now:-
int hour = DateTime.Now.Hour;
int mins = DateTIme.Now.Minute
if(hour>10 && mins >30)
{
string lateBy = "You are late by:"+ //????? how do I calculate this?
}
Any help would be great
Use TimeSpan to find the difference between the 2 datetime values, and use the TotalMinutes property to get the difference in minutes.
DateTime today = DateTime.Today;
DateTime start = new DateTime(today.Year,today.Month,today.Day,10,30,00);
DateTime now = DateTime.Now;
int hour = now.Hour;
int mins = now.Minute;
TimeSpan ts = now.Subtract(start);
if(ts.TotalMinutes > 0) //Time now is after 10:30
{
string lateBy = "You are late by:"+ ts.TotalMinutes.ToString();
}
Ignoring dates and assuming it is always the same day as the 10:30 deadline day:
string lateBy = "You are late by:"+ ((hour-10)*60 + mins-30) + " minutes";
Note this only works before midnight, i.e. for the same day.
Since both are DateTime, you can make use of DateTime.Subract
DateTime a = new DateTime(2014, 06, 20, 10, 30, 00);
DateTime b = DateTime.Now;
Console.WriteLine("You are late by:"+b.Subtract(a).TotalMinutes +"minutes");
Console.ReadLine();

how to subtract previous date from current date using c# [duplicate]

This question already has answers here:
C#: how do I subtract two dates?
(11 answers)
Closed 10 years ago.
i want to subtract previous date from current date. previous date may be 2 months and 15 days or 1 year 9 month and 10 days... like this etc... So please how can i write the Coding in C#. thanks a lot.
Any answer using TimeSpan will not be able to give you "2 months and 15 days" - as the length of a month changes over time.
Doing this using the base class libraries is a pain... which is one of the reasons I started the Noda Time project. Amongst its other features, it allows you to determine the Period between to dates (or dates and times, etc).
For example, let's see how long I've been on Stack Overflow:
LocalDate today = new LocalDate(2013, 2, 8);
LocalDate start = new LocalDate(2008, 9, 26);
// This defaults to using year, month, day units. You can specify alternatives.
Period period = Period.Between(start, today);
Console.WriteLine("{0} years; {1} months; {2} days",
period.Years, period.Months, period.Days);
Output:
4 years; 4 months; 13 days
Or if you actually wanted to subtract a period from a date (the question isn't very clear) you can do that too:
Period period = new PeriodBuilder { Years = 4, Months = 4, Days = 13 }.Build();
LocalDate today = new LocalDate(2013, 2, 8);
LocalDate start = today - period;
Console.WriteLine(start);
Output:
25 September 2008
Note that this doesn't give September 26th, because of the somewhat crazy nature of date/time arithmetic. If you added the period to September 26th you'd get today... but that's not the same thing. Treat this as a warning that you need to be really careful about describing what you want to achieve :)
This second side you can do with the BCL fairly easily though:
DateTime today = new DateTime(2013, 2, 8);
DateTime start = today.PlusYears(-4).PlusMonths(-4).PlusDays(-13);
There's no BCL type to represent that "years, months, days" value though.
Your question is a little confusing. Do you want to subtract one date from another date, or do you want to subtract a period of time from a date.
1. Subtract one date from another date:
DateTime previousDate = new DateTime(1990, 12, 12);
DateTime currentDate = DateTime.UtcNow;
TimeSpan difference = currentDate - previousDate;
You can then use the TimeSpan methods to get the difference in various units of time as you like.
Here's more info on TimeSpan: http://msdn.microsoft.com/en-us/library/system.timespan.aspx
2. Subtract a period of time from a date
DateTime currentDate = DateTime.UtcNow;
TimeSpan periodOfTime = new TimeSpan(12, 12, 0, 0);
DateTime newDate = currentDate - periodOfTime;
However, you'll have to calculate yourself what the length of a month is, if that's what you want.
You can use DateTime.Subtract.
Examples from article:
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;
TimeSpan timeSpan = new TimeSpan(2,2,0);
DateTime dateTime = DateTime.Now.Subtract(timeSpan);
When you subtract two date in C# you get a TimeSpan object.
You can acces different properties of it to get the actual days, hours, minutes etc. taht it represents:
DateTime a;
DateTime b;
//assign some values
TimeSpan span = a.Subtract(b);
Console.WriteLine("Days: " + span.Days);
The following should do.
TimeSpan diff = DateTime.Now - previousDate;

Categories

Resources