Today is nth day of year
Calendar calendar = Calendar.getInstance();
int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
Or using Joda-API
DateTime dt = new DateTime();
int dayOfYear = dt.getDayOfYear();
If you need 'th'
part, use switch statement
switch (dayOfYear > 20 ? (dayOfYear % 10) : dayOfYear) {
case 1: return dayOfYear + "st";
break;
case 2: return dayOfYear + "nd";
break;
case 3: return dayOfYear + "rd";
break;
default: return dayOfYear + "th";
break;
}
Get the nth day of a year
It looks like the idea you're going for is a recursive approach that decrements by month.
static int dayNumberInYear(int day, Month month, int year)
{
if(!month.equals(Month.JANUARY)) {
return day + dayNumberInYear(numberOfDaysInMonth(month.minus(1), year), month.minus(1), year);
} else {
return day;
}
}
Note that in this recursive approach, the base case is that it's January and we simply return the current day in January. Otherwise we add the day of the current month and then all the days in every prior month.
It could also be done as a for-loop.
static int dayNumberInYearByLoop(int day, Month month, int year) {
int totalDays = day;
for (int i = month.getValue();i>1;i--) {
totalDays += numberOfDaysInMonth(Month.of(i), year);
}
return totalDays;
}
You can mess around with my code here: https://repl.it/repls/ConcreteDarkgreenSequence
How to get day of year number in Java for a specific date object?
Calendar#get(Calendar.DAY_OF_YEAR);
Get DateTime of the next nth day of the month
Why not just do?
private DateTime GetNextDate(DateTime dt, int DesiredDay)
{
if (DesiredDay >= 1 && DesiredDay <= 31)
{
do
{
dt = dt.AddDays(1);
} while (dt.Day != DesiredDay);
return dt.Date;
}
else
{
throw new ArgumentOutOfRangeException();
}
}
Calculate the N th day of the previous year
You could do:
from datetime import datetime, timedelta
date_string = '2020-03-09'
# Parse the string to a datetime.date object
date = datetime.strptime(date_string, '%Y-%m-%d')
# Get the number N of the day in the year
N = date.timetuple().tm_yday
# Take 1st of january of last year and add N-1 days
N_last_year = (
date.replace(year=date.year-1, month=1, day=1) +
timedelta(days=N-1)
)
print(N_last_year.date())
Or, another funny solution based on leap years. It is based on the fact that the Nth day of last year is the same as this year's, except if the date is after 29th february and there is a leap year somewhere.
from datetime import datetime, timedelta
def leap(year: int) -> bool:
# Returns True if year is a leap year, False otherwise
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
date_string = '2020-03-09'
# Parse the string to a datetime.date object
date = datetime.strptime(date_string, '%Y-%m-%d')
# Get the number N of the day in the year
N = date.timetuple().tm_yday
date_last_year = date.replace(year=date.year-1)
# Do the cool thing
if date.month >= 3:
if leap(date.year):
date_last_year += timedelta(days=1)
elif leap(date.year-1):
date_last_year += timedelta(days=-1)
print(date_last_year.date())
Calculate number of days until nth day of month
Perhaps this can be simplified but I'd break it down into the following logic:
- If the day - i.e. the 23rd - is less than or equal to 20, then take the difference between the two.
- Otherwise, calculate the 20th day of the next month, and take the difference.
Something like this:
=IF(DAY(A2)<=20,20-DAY(A2),DATE(YEAR(EOMONTH(A2,1)),MONTH(EOMONTH(A2,1)),20)-A2)
JavaScript calculate the day of the year (1 - 366)
Following OP's edit:
var now = new Date();var start = new Date(now.getFullYear(), 0, 0);var diff = now - start;var oneDay = 1000 * 60 * 60 * 24;var day = Math.floor(diff / oneDay);console.log('Day of year: ' + day);
Related Topics
How to Solve the "Double-Checked Locking Is Broken" Declaration in Java
Encoding Url Query Parameters in Java
Variable Length (Dynamic) Arrays in Java
How to Make an Array of Arrays in Java
Turning Off Hibernate Logging Console Output
Sort Arrays of Primitive Types in Descending Order
Singleton Class with Several Different Classloaders
Can Not Find the Tag Library Descriptor for "Http://Java.Sun.Com/Jsp/Jstl/Core"
How to Get Timezone from Android Mobile
Onactivityresult() Not Called in New Nested Fragment API
How to Send Data from Dialogfragment to a Fragment
How to Catch a Firebase Auth Specific Exceptions