how get yesterday and tomorrow datetime in c# - c#

I have a code:
int MonthNow = System.DateTime.Now.Month;
int YearNow = System.DateTime.Now.Year;
int DayNow = System.DateTime.Now.Day;
How can I get yesterday and tomorrow day, month and year in C#?
Of course, I can just write:
DayTommorow = DayNow +1;
but it may happen that tomorrow is other month or year. Are there in C# built-in tools to find out yesterday and today?

DateTime tomorrow = DateTime.Today.AddDays(1);
DateTime yesterday = DateTime.Today.AddDays(-1);

You can find this info right in the API reference.
var today = DateTime.Today;
var tomorrow = today.AddDays(1);
var yesterday = today.AddDays(-1);

You should do it this way, if you want to get yesterday and tomorrow at 00:00:00 time:
DateTime yesterday = DateTime.Today.AddDays(-1);
DateTime tomorrow = DateTime.Today.AddDays(1); // Output example: 6. 02. 2016 00:00:00
Just bare in mind that if you do it this way:
DateTime yesterday = DateTime.Now.AddDays(-1);
DateTime tomorrow = DateTime.Now.AddDays(1); // Output example: 6. 02. 2016 18:09:23
then you will get the current time minus one day, and not yesterday at 00:00:00 time.

Today :
DateTime.Today
Tomorrow :
DateTime.Today.AddDays(1)
Yesterday :
DateTime.Today.AddDays(-1)

You want DateTime.Today.AddDays(1).

Use DateTime.AddDays() (MSDN Documentation DateTime.AddDays Method).
DateTime tomorrow = DateTime.Now.AddDays(1);
DateTime yesterday = DateTime.Now.AddDays(-1);

The trick is to use "DateTime" to manipulate dates; only use integers and strings when you need a "final result" from the date.
For example (pseudo code):
Get "DateTime tomorrow = Now + 1"
Determine date, day of week, day of month - whatever you want - of the resulting date.

To get "local" yesterday in UTC.
var now = DateTime.Now;
var yesterday = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0, DateTimeKind.Utc).AddDays(-1);

Beware of adding an unwanted timezone to your results, especially if the date is going to be sent out via a Web API. Use UtcNow instead, to make it timezone-less.

Related

Easily calculate the time before midnight in C#

I have a function which is already compact, i wanted to know if there was better (like a DateTime functionality already included).
Currently i use this:
DateTime today = DateTime.Now;
DateTime tomorrow = new DateTime(today.Year, today.Month, today.Day, 0, 0, 0).AddDays(1);
double remaining = (tomorrow - today).TotalMilliseconds;
Thank for reading.
You can simplify the tomorrow value by just doing this and taking the benefit of DateTime.Today:
DateTime tomorrow = DateTime.Today.AddDays(1);
So your code will be easy to read:
DateTime today = DateTime.Now;
DateTime tomorrow = DateTime.Today.AddDays(1);
double remaining = (tomorrow - today).TotalMilliseconds;
You can create extension for DateTime
public static class DateExtensions
{
public static double GetNextDayRemainingMs(this DateTime dateTime)
{
return (dateTime.AddDays(1).Date - dateTime).TotalMilliseconds;
}
}
Usage
DateTime.Now.GetNextDayRemainingMs();
You can try following code
(DateTime.Today.AddDays(1)-DateTime.Now).TotalMilliseconds
Instead of defining instance for tomorrow variable you can use .AddDate(1).Date property
.AddDate(1) will add one day to DateTime.Now and .Date property
will give you only date and sets time to 00.
DateTime today = DateTime.Now;
double remaining = (today.AddDate(1).Date - today).TotalMilliseconds;
Or (Elegant way)
You can use Today property of DateTime.
An object that is set to today's date, with the time component set to
00:00:00.
double remaining = (DateTime.Today.AddDays(1)-DateTime.Now).TotalMilliseconds

Calculate Last Day of the Next Month

I am attempting to use the DateTime function in C# to calculate the last day of next month.
For example, today is December 17th 2015. I want the DateTime function to return January 31st 2016 (the last day of next month).
I am using the following to calculate the first day of next month (this works):
DateTime firstDayNextMonth = DateTime.Today.AddDays(-DateTime.Now.Day+1).AddMonths(1);
DateTime reference = DateTime.Now;
DateTime firstDayThisMonth = new DateTime(reference.Year, reference.Month, 1);
DateTime firstDayPlusTwoMonths = firstDayThisMonth.AddMonths(2);
DateTime lastDayNextMonth = firstDayPlusTwoMonths.AddDays(-1);
DateTime endOfLastDayNextMonth = firstDayPlusTwoMonths.AddTicks(-1);
Demo: http://rextester.com/AKDI52378
//system date or any date u want this case it is a calendar picker - 22/03/2016
DateTime today = dtpFrom.Value;
//Add a month to your date example , it now becomes - 22/04/2016
DateTime endOfMonth = new DateTime(today.Year, today.Month,today.Day).AddMonths(1);
//Get the last date off the above which is - 30
int getlastday = DateTime.DaysInMonth(endOfMonth.Year, endOfMonth.Month);
//Now set the date to the value which will be the last day off the next month - 30/04/2016
DateTime newDate = new DateTime(endOfMonth.Year, endOfMonth.Month, getlastday);
DateTime.DaysInMonth(DateTime.Now.AddMonths(1).Year, DateTime.Now.AddMonths(1).Month);
var lastDayInNextMonth = DateTime.DaysInMonth(DateTime.Now.AddMonths(1).Year, DateTime.Now.AddMonths(1).Month );
# Ben : DateTime.Now.AddMonths(1) will add 1 month to the current date not substract 11 months.
DateTime.Now.AddMonths(1).Year will give 2016 not 2015 refer the attached image
try this:
int Day= DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month+1>12 ? 01 : DateTime.Now.Month+1 );

Set time value to tomorrow 9 am

How can I set certain DateTime value to tomorrow 9:00 AM
For example:
DateTime startTime = new DateTime.Now.AddDays(1).//setTime to 9:00 AM
Is there some SetDateTime value functionality that I don't know?
You can use two methods
DateTime.Today.AddDays(1).AddHours(9)
You can use this DateTime constructor like;
DateTime tomorrow = new DateTime(DateTime.Now.Year,
DateTime.Now.Month,
DateTime.Now.Day + 1,
9,
0,
0);
Console.WriteLine(tomorrow);
Output will be;
18.03.2014 09:00:00
As CompuChip mentioned, this throws exception if the current day is the last day of the month.
Better you can use DateTime.Today property with AddDays(1) and AddHours(9) because it get's to midnight of the current day. Like;
DateTime tomorrow = DateTime.Today.AddDays(1).AddHours(9);
DateTime dt=DateTime.Now;
DateTime Tomorrow = new DateTime(dt.Year,dt.Month,dt.Day+1,9,0,0);

How to set current time to a value

I was just wondering if there is a way to get the current time and set it into a value.
If its 12:06 AM.. I want to get that time and set it into currentTime.
Example
float currentTime = 0;
currentTime = 12.06;
As others have mentioned, the DateTime class would be ideal for this, and to work out the difference between 2 date/times:
DateTime end = DateTime.Now;
DateTime start = new DateTime(2011, 12, 5, 12, 6,0);
double hours = (end - start).TotalHours;
The subtraction of DateTime objects results in a TimeSpan object that you can use to see the hours/minutes etc.
try DateTime class
DateTime dt = DateTime.Now;
Is this what you're looking for?
DateTime currentTime;
currentTime = DateTime.Now;
Don't use floats or strings. You can do all kinds of cool things using DateTime.
Here's how you'd get the hours that someone worked:
var clockIn = new DateTime(2011,12,4,9,0,0); // December 4th, 9 AM
var clockOut = new DateTime(2011,12,4,17,0,0); // December 4th, 5 PM
var duration = clockOut - clockIn; // TimeSpan
Console.Write(duration.TotalHours); // 8
A few people have mentioned how, but as a 'better' recommendation you should use
DateTime currentTime = DateTime.UtcNow
Otherwise you have issues when the clocks go back, if your timing code is run on those days. (plus it is far easier to alter the UTC time to local time than it is to convert a '1am' to UTC (as there will be two of them when the clocks go back)
Well if you really what it as a float then try:
var currentDate = DateTime.Now;
float currentTime = float.Parse((currentDate.Hour > 12 ? currentDate.Hour -12 :
currentDate.Hour) + "." + currentDate.Minute);
I wouldn't recommend comparing dates or time with floats. A better options would be to use timespans.
You should be using a Timespan instance for time related values, you can use the flexibility to get the required values like
TimeSpan ts = DateTime.Now.TimeOfDay;
ts.ToString("hh:mm") // this could be what you are looking for
You could then use ts.TotalHours which would give you fractional hours (as a double) else you could construct a string specifically using ts.Hours ..ts.Minutes play around and it could be prove useful.
Try the following:
DateTime StartTime=StartTime value;
DateTime CurrentTime=DateTime.Now;
TimeSpan dt = CurrentTime.Subtract(StartTime);
In dt you will get a working time period.
If you want to have the difference between two times, then do this:
DateTime dateOne = DateTime.Parse(enteredTime);
DateTime dateTwo = DateTime.Now;
TimeSpan difference = dateOne - dateTwo;

How to subtract a year from the datetime?

How to subtract a year from current datetime using c#?
var myDate = DateTime.Now;
var newDate = myDate.AddYears(-1);
DateTime oneYearAgoToday = DateTime.Now.AddYears(-1);
Subtracting a week:
DateTime weekago = DateTime.Now.AddDays(-7);
It might be worth noting that the accepted answer may adjust the date by either 365 days or 366 days due to leap years (it gets the date for the same day of the month one year ago, with the exception of 29th February where it returns 28th February).
In the vast majority of cases this is exactly what you want however if you are treating a year as a fixed unit of time (e.g. the Julian year) then you would need to subtract from either days;
var oneFullJulianYearAgo = DateTime.Now.AddDays(-365.25);
or seconds;
var oneFullJulianYearAgo = DateTime.Now.AddSeconds(-31557600);

Categories

Resources