Strange result when adding one year to java.util.Calendar - java

Initialize java.util.Calendar with May, 31 1900. Then add one year to it twenty times.
Here's code:
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*
fun main(args : Array<String>) {
val f = SimpleDateFormat("yyyy.dd.MM")
val cal = Calendar.getInstance()
cal.set(1900, Calendar.MAY, 31)
for(i in 1..20) {
println(f.format(cal.time))
cal.add(Calendar.YEAR, 1)
}
}
The output is following:
1900.31.05
1901.31.05
1902.31.05
1903.31.05
1904.31.05
1905.31.05
1906.31.05
1907.31.05
1908.31.05
1909.31.05
1910.31.05
1911.31.05
1912.31.05
1913.31.05
1914.31.05
1915.31.05
1916.31.05
1917.31.05
1918.01.06
1919.01.06
Why I get June, 1 instead of May, 31 since 1918?
UPD: with time information
1917.31.05 23:38:50.611
1918.01.06 01:38:50.611
If this is DST invention, how do I prevent that?

You seem to be running your code in a timezone that changed its offset by two hours in 1917 or 1918. That is, the number of hours ahead or behind UTC changed. I've no idea why your timezone would have done that, but I'm sure there's a good historical reason for it.
If you're only interested in dates, without the Time component, use the java.time.LocalDate class, which effectively represents a day, month and year only. It's not subject to any daylight savings anomalies.
LocalDate today = LocalDate.now();
or
LocalDate moonLanding = LocalDate.of(1969, 7, 20);

I am assuming that you are in Europe/Moscow time zone. Turing85 in a comment correctly spotted the cause of the behaviour you observed: In 1918 summer time (DST) in your time zone began on May 31. The clock was moved forward from 22:00 to 24:00, that is, by two hours. Your Calendar object is aware of this and therefore refuses to give 23:38:50.611 on this date. Instead it picks the time 2 hours later, 1918.01.06 01:38:50.611. Now the month and day-of-month have changed to 1st of June.
Unfortunately this change is kept in the Calendar and carried on to the following year.
If this is DST invention, how do I prevent that?
Thomas Kläger in a comment gave the right solution: If you only need the dates, use LocalDate from java.time:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("uuuu.dd.MM");
LocalDate date = LocalDate.of(1900, Month.MAY, 31);
for (int i = 1; i <= 20; i++) {
System.out.println(date.format(dateFormatter));
date = date.plusYears(1);
}
Output (abbreviated):
1900.31.05
1901.31.05
…
1917.31.05
1918.31.05
1919.31.05
The “local” in LocalDate means “without timezone” in java.time jargon, so this is guaranteed to keep you free of surprises from time zone anomalies.
If you need a time, you may consider LocalDateTime, but since this is without time zone too, it will give you the non-existing time of 1918.31.05 23:38:50.611, so maybe not.
An alternative thing you may consider is adding the right number of years to your origin of 1900.31.05 23:38:50.611. Then at least you will only have surprises in years where you hit a non-existing time. I am using ZonedDateTime for this demonstration:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu.dd.MM HH:mm:ss.SSS");
ZonedDateTime originalDateTime = ZonedDateTime.of(1900, Month.MAY.getValue(), 31,
23, 30, 50, 611000000, ZoneId.of("Europe/Moscow"));
for (int i = 0; i < 25; i++) {
System.out.println(originalDateTime.plusYears(i).format(formatter));
}
Output:
1900.31.05 23:30:50.611
1901.31.05 23:30:50.611
…
1917.31.05 23:30:50.611
1918.01.06 01:30:50.611
1919.01.06 00:30:50.611
1920.31.05 23:30:50.611
…
1924.31.05 23:30:50.611
Again in 1919 summer time began on May 31. This time the clock was only advanced by 1 hour, from 23 to 24, so you get only 1 hour later than the imaginary time of 23:30:50.611.
I am recommending java.time for date and time work, not least when doing math on dates like you do. The Calendar class is considered long outmoded. java.time was designed acknowledging that Calendar and the other old classes were poorly designed. The modern ones are so much nicer to work with.
How could I be sure it was Moscow?
In no other time zone than Europe/Moscow is the time of 1918.31.05 23:38:50.611 nonexistent. I checked:
LocalDateTime dateTime = LocalDateTime.of(1918, Month.MAY, 31, 23, 38, 50, 611000000);
for (String zid : ZoneId.getAvailableZoneIds()) {
ZonedDateTime zdt = dateTime.atZone(ZoneId.of(zid));
LocalDateTime newDateTime = zdt.toLocalDateTime();
if (! newDateTime.equals(dateTime)) {
System.out.println(zid + ": -> " + zdt + " -> " + newDateTime);
}
}
Output:
Europe/Moscow: -> 1918-06-01T01:38:50.611+04:31:19[Europe/Moscow] -> 1918-06-01T01:38:50.611
W-SU: -> 1918-06-01T01:38:50.611+04:31:19[W-SU] -> 1918-06-01T01:38:50.611
“W-SU” is a deprecated name for the same time zone, it stands for Western Soviet Union.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Time Changes in Moscow Over the Years
List of tz database time zones showing W-SU as deprecated.
An old message on an IANA mailing list stating “But long ago … we based the name on some more-political entity than a city name. For example, we used "W-SU" for the western Soviet Union…”

Related

I want to get last date of the month and add n months to it but calendar instance is taking only 30 days in Java

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calender = Calendar.getInstance();
calender.set(Calendar.DAY_OF_MONTH, calender.getActualMaximum(Calendar.DATE));
int months = 1;
calender.add(Calendar.MONTH, months );
String time = sdf .format(calender .getTime());
System.out.println(time);
Since current month is April and last date is 2020-04-30
Next month last date I should get 2020-05-31
but I am getting last date as 2020-05-30
Any thing am i doing wrong ?
java.time
I recommend that you use java.time, the modern Java date and time API, for your date work. It’s much nicer to work with than the old classes Calendar and SimpleDateFormat.
LocalDate endOfNextMonth =
YearMonth // Represent an entire month in a particular year.
.now(ZoneId.of("Europe/Volgograd")) // Capture the current year-month as seen in a particular time zone. Returns a `YearMonth` object.
.plusMonths(1) // Move to the next month. Returns another `YearMonth` object.
.atEndOfMonth(); // Determine the last day of that year-month. Returns a `LocalDate` object.
String time = endOfNextMonth.toString(); // Represent the content of the `LocalDate` object by generating text in standard ISO 8601 format.
System.out.println("Last day of next month: " + time);
Output when running today:
Last day of next month: 2020-05-31
A YearMonth, as the name maybe says, is a year and month without day of month. It has an atEndOfMonth method that conveniently gives us the last day of the month as a LocalDate. A LocalDate is a date without time of day, so what we need here. And its toString method conveniently gives the format that you wanted (it’s ISO 8601).
Depending on the reason why you want the last day of another month there are a couple of other approaches you may consider. If you need to handle date ranges that always start and end on month boundaries, you may either:
Represent your range as a range of YearMonth objects. Would this free you from knowing the last day of the month altogether?
Represent the end of your range as the first of the following month exclusive. Doing math on the 1st of each month is simpler since it is always day 1 regardless of the length of the month.
What went wrong in your code?
No matter if using Calendar, LocalDate or some other class you need to do things in the opposite order: first add one month, then find the end of the month. As you know, months have different lengths, so the important part is getting the end of that month where you want to get the last day. Putting it the other way: setting either a LocalDate or a Calendar to the last day of the month correctly sets it to the last day of the month in qustion but does not instruct it to stay at the last day of the month after subsequent changes to its value, such as adding a month. If you add a month to April 29, you get May 29. If you add a month to April 30, you get May 30. Here it doesn’t matter that 30 is the last day of April while 30 is not the last day of May.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601
You'd better use LocalDate like this:
LocalDate now = LocalDate.now();
LocalDate lastDay = now.withDayOfMonth(now.lengthOfMonth());
LocalDate nextMonth = lastDay.plusMonths(1);
Don't use deprecated classes from java.util.*.
Use classes from java.time.*.
Example with LocalDate :
public class Testing {
public static void main(String args[]) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.now();
int months = 1;
date = date.plusMonths(months);
date = date.withDayOfMonth(date.lengthOfMonth());
System.out.println(date.format(dateTimeFormatter));
}
}
Output :
2020-05-31
Example with Calendar :
public class Testing {
public static void main(String args[]) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calender = Calendar.getInstance();
int months = 1;
calender.add(Calendar.MONTH, months);
calender.set(Calendar.DAY_OF_MONTH, calender.getActualMaximum(Calendar.DAY_OF_MONTH));
String time = sdf.format(calender.getTime());
System.out.println(time);
}
}
Output :
2020-05-31

Instant time from week of year

I need to get Instant time from week number of year. Now I'm using old Calendar API to calculate time:
int week = 1; // week of year
final Calendar cal = new GregorianCalendar();
cal.set(0, 1, 0, 0, 0, 0); // reset calendar
cal.set(Calendar.YEAR, Year.now().getValue());
cal.set(Calendar.WEEK_OF_YEAR, week);
cal.setTimeZone(TimeZone.getTimeZone(ZoneOffset.UTC));
final Instant start = cal.getTime().toInstant();
final Instant end = start.plus(Period.ofWeeks(1));
Is it possible to get Instant from week of year using new Java time API (java.time package)?
WeekFields wf = WeekFields.of(Locale.getDefault());
int week = 1; // week of year
LocalDate startDate = LocalDate.now(ZoneOffset.UTC)
.with(wf.weekOfWeekBasedYear(), week)
.with(wf.dayOfWeek(), 1);
Instant startInstant = startDate.atStartOfDay(ZoneOffset.UTC).toInstant();
LocalDate endDate = startDate.plusWeeks(1);
Instant endInstant = endDate.atStartOfDay(ZoneOffset.UTC).toInstant();
System.out.println("" + startInstant + " - " + endInstant);
My locale uses ISO week numbers. The output here was:
2019-12-29T00:00:00Z - 2020-01-05T00:00:00Z
If you want ISO weeks independently of the locale, set wf to WeekFields.ISO. If you want some other week numbering scheme, set wf accordingly.
In case any other readers were wondering, Kirill is defining the end of the week as the first moment of the following week. This is recommended. It’s known as using half-open intervals for time intervals.
I also agree with the question that one should clearly prefer using java.time for this task rather than Calendar. Calendar is poorly designed and long outdated, and I believe that the code using java.time is clearer to read.
Furthermore, the code in the question using Calendar doesn’t set the day to the first day of the week, so will not give you that day. And while I haven’t tested, I suspect that the code will sometimes produce unexpected results around New Year.
My code using WeekFields from java.time will stay within the current week-based year, which is not the same as the calendar year. For example, if I had run it on December 30, 2019, it would still have given med week 1 of 2020 because we were already in that week.
You could adjust the week using the following methods:
LocalDateTime localDateTime = LocalDateTime.of(2020, 1, 1, 0, 0);
System.out.println(localDateTime); //2020-01-01T00:00
localDateTime = localDateTime.with(ChronoField.ALIGNED_WEEK_OF_YEAR, 2);
System.out.println(localDateTime); //2020-01-08T00:00
localDateTime = localDateTime.plusWeeks(10);
System.out.println(localDateTime); //2020-03-18T00:00
and to parse it to Instant depends on what class from the API you are using:
LocalDateTime.now().toInstant(ZoneOffset.of("+04:00"));
ZonedDateTime.now().toInstant();
The LocalDateTime doest not have a Zone, so you must a provide a ZoneOffset to parse it to a Instant.
In order to set the month you can use this lambda expression:
LocalDate.now().with(temporal
-> temporal.with(ChronoField.ALIGNED_WEEK_OF_YEAR, 1l)
);
Now get instant is easy:
LocalDate localDate = LocalDate.now().with(temporal
-> temporal.with(ChronoField.ALIGNED_WEEK_OF_YEAR, 1l)
);
Instant instant = localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
If you don't want cto change time, then you can use this instead of last line:
Instant instant = localDate.atTime(LocalTime.now()).atZone(ZoneId.systemDefault()).toInstant();

How can I add validation onto a Date that rolls into another year using Java Date class

I'm currently trying to improve an aspect of a project of mine.
Users are allowed to do a specific task, but they must book a date in order to do it.
I'm trying to add some more realistic validation onto my date, so that the tasks can't be booked a year in advance, and only a few months.
Currently I'm only checking the year of the input and comparing it to the current year, so if they try to assign themselves a task on 31st of December, they will not be able to because any date they enter will roll over to the next year, and my validation prevents this.
How can I make it so it will check the amount of months, rather than the current year?
I am able to do this for the current year, I just get stuck when the year comes to december and the months roll into January again.
Edit:
Those looking for a way to fix this, go here: Calculating the difference between two Java date instances
Because the lengths of months are different, I would test the number of days. Here's a couple of utility methods that get the job done in one line:
// Tests if the end date is within so many days of the start date
public static boolean isWithinRange(int days, Date end, Date start) {
return TimeUnit.DAYS.convert(end.getTime() - start.getTime(), TimeUnit.MILLISECONDS) < days;
}
// Tests if the specified date is within so many days of today
public static boolean isWithinRange(int days, Date end) {
return isWithinRange(days, end, new Date());
}
Here I've used the TimeUnit class to do the calculation for me.
you can use your own method. Something like this
public boolean isLaterDay(Date date, Date reference) {
if (date.getYear () > reference.getYear ()) return true;
if (date.getYear () < reference.getYear ()) return false;
return (date.getMonth() > reference.getMonth());
}
Another way of doing this would be as follows.
boolean validDate(Calendar inputDate)
{
Calendar validationDate = Calendar.getInstance().add(Calendar.MONTH, numOfMonths);
return inputDate.before(validationDate);
}
You can do something like this to validate the time
private static final int MAX_MONTHS_IN_ADVANCE = 3;
public boolean isValidDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, MAX_MONTHS_IN_ADVANCE);
return date.before(calendar.getTime());
}
Using the Joda-Time library:
If ( dateTimeInQuestion.isBefore( DateTime.now().plusMonths(3) )
java.time
The modern way to do this work is with the java.time classes. These classes supplant the troublesome old legacy date-time classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
ZoneId z = ZoneId.of( “America/Montreal” );
LocalDate today = LocalDate.now( z );
Construct the date desired by the user.
LocalDate ld = LocalDate.of( 2016 , 12 , 31 );
Determine the boundaries, say six months ago and six months from now.
LocalDate past = today.minusMonths( 6 );
LocalDate future = today.plusMonths( 6 );
You can compare LocalDate objects with isBefore, isAfter, equals, and compareTo.
Let's test by asking if the user's date is equal to or later than the before boundary (in other words, not before) AND the user's date is before the future boundary. This comparison uses the Half-Open approach commonly used with date-time work. The beginning is inclusive while the ending is exclusive.
Boolean validDate = ( ( ! ld.isBefore( past) ) && ( ld.isBefore( future) ) );
Interval
If you often work with the spans of time, consider using the Interval class found in the ThreeTen-Extra project that adds onto the java.time classes. That class has handy methods such as contains, abuts, overlaps, and more.

How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

How can I get the year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java? I would like to have them as Strings.
You can use the getters of java.time.LocalDateTime for that.
LocalDateTime now = LocalDateTime.now();
int year = now.getYear();
int month = now.getMonthValue();
int day = now.getDayOfMonth();
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();
int millis = now.get(ChronoField.MILLI_OF_SECOND); // Note: no direct getter available.
System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);
Or, when you're not on Java 8 yet, make use of java.util.Calendar.
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1; // Note: zero based!
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int millis = now.get(Calendar.MILLISECOND);
System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);
Either way, this prints as of now:
2010-04-16 15:15:17.816
To convert an int to String, make use of String#valueOf().
If your intent is after all to arrange and display them in a human friendly string format, then better use either Java8's java.time.format.DateTimeFormatter (tutorial here),
LocalDateTime now = LocalDateTime.now();
String format1 = now.format(DateTimeFormatter.ISO_DATE_TIME);
String format2 = now.atZone(ZoneId.of("GMT")).format(DateTimeFormatter.RFC_1123_DATE_TIME);
String format3 = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss", Locale.ENGLISH));
System.out.println(format1);
System.out.println(format2);
System.out.println(format3);
or when you're not on Java 8 yet, use java.text.SimpleDateFormat:
Date now = new Date(); // java.util.Date, NOT java.sql.Date or java.sql.Timestamp!
String format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH).format(now);
String format2 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH).format(now);
String format3 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH).format(now);
System.out.println(format1);
System.out.println(format2);
System.out.println(format3);
Either way, this yields:
2010-04-16T15:15:17.816
Fri, 16 Apr 2010 15:15:17 GMT
20100416151517
See also:
Java string to date conversion
Switch to joda-time and you can do this in three lines
DateTime jodaTime = new DateTime();
DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.SSS");
System.out.println("jodaTime = " + formatter.print(jodaTime));
You also have direct access to the individual fields of the date without using a Calendar.
System.out.println("year = " + jodaTime.getYear());
System.out.println("month = " + jodaTime.getMonthOfYear());
System.out.println("day = " + jodaTime.getDayOfMonth());
System.out.println("hour = " + jodaTime.getHourOfDay());
System.out.println("minute = " + jodaTime.getMinuteOfHour());
System.out.println("second = " + jodaTime.getSecondOfMinute());
System.out.println("millis = " + jodaTime.getMillisOfSecond());
Output is as follows:
jodaTime = 2010-04-16 18:09:26.060
year = 2010
month = 4
day = 16
hour = 18
minute = 9
second = 26
millis = 60
According to http://www.joda.org/joda-time/
Joda-Time is the de facto standard date and time library for Java.
From Java SE 8 onwards, users are asked to migrate to java.time
(JSR-310).
// Java 8
System.out.println(LocalDateTime.now().getYear()); // 2015
System.out.println(LocalDateTime.now().getMonth()); // SEPTEMBER
System.out.println(LocalDateTime.now().getDayOfMonth()); // 29
System.out.println(LocalDateTime.now().getHour()); // 7
System.out.println(LocalDateTime.now().getMinute()); // 36
System.out.println(LocalDateTime.now().getSecond()); // 51
System.out.println(LocalDateTime.now().get(ChronoField.MILLI_OF_SECOND)); // 100
// Calendar
System.out.println(Calendar.getInstance().get(Calendar.YEAR)); // 2015
System.out.println(Calendar.getInstance().get(Calendar.MONTH ) + 1); // 9
System.out.println(Calendar.getInstance().get(Calendar.DAY_OF_MONTH)); // 29
System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)); // 7
System.out.println(Calendar.getInstance().get(Calendar.MINUTE)); // 35
System.out.println(Calendar.getInstance().get(Calendar.SECOND)); // 32
System.out.println(Calendar.getInstance().get(Calendar.MILLISECOND)); // 481
// Joda Time
System.out.println(new DateTime().getYear()); // 2015
System.out.println(new DateTime().getMonthOfYear()); // 9
System.out.println(new DateTime().getDayOfMonth()); // 29
System.out.println(new DateTime().getHourOfDay()); // 7
System.out.println(new DateTime().getMinuteOfHour()); // 19
System.out.println(new DateTime().getSecondOfMinute()); // 16
System.out.println(new DateTime().getMillisOfSecond()); // 174
// Formatted
// 2015-09-28 17:50:25.756
System.out.println(new Timestamp(System.currentTimeMillis()));
// 2015-09-28T17:50:25.772
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH).format(new Date()));
// Java 8
// 2015-09-28T17:50:25.810
System.out.println(LocalDateTime.now());
// joda time
// 2015-09-28 17:50:25.839
System.out.println(DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.SSS").print(new org.joda.time.DateTime()));
tl;dr
ZonedDateTime.now( // Capture current moment as seen in the wall-clock time used by the people of a particular region (a time zone).
ZoneId.of( "America/Montreal" ) // Specify desired/expected time zone. Or pass `ZoneId.systemDefault` for the JVM’s current default time zone.
) // Returns a `ZonedDateTime` object.
.getMinute() // Extract the minute of the hour of the time-of-day from the `ZonedDateTime` object.
42
ZonedDateTime
To capture the current moment as seen in the wall-clock time used by the people of a particular region (a time zone), use ZonedDateTime.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Call any of the many getters to pull out pieces of the date-time.
int year = zdt.getYear() ;
int monthNumber = zdt.getMonthValue() ;
String monthName = zdt.getMonth().getDisplayName( TextStyle.FULL , Locale.JAPAN ) ; // Locale determines human language and cultural norms used in localizing. Note that `Locale` has *nothing* to do with time zone.
int dayOfMonth = zdt.getDayOfMonth() ;
String dayOfWeek = zdt.getDayOfWeek().getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;
int hour = zdt.getHour() ; // Extract the hour from the time-of-day.
int minute = zdt.getMinute() ;
int second = zdt.getSecond() ;
int nano = zdt.getNano() ;
The java.time classes resolve to nanoseconds. Your Question asked for the fraction of a second in milliseconds. Obviously, you can divide by a million to truncate nanoseconds to milliseconds, at the cost of possible data loss. Or use the TimeUnit enum for such conversion.
long millis = TimeUnit.NANOSECONDS.toMillis( zdt.getNano() ) ;
DateTimeFormatter
To produce a String to combine pieces of text, use DateTimeFormatter class. Search Stack Overflow for more info on this.
Instant
Usually best to track moments in UTC. To adjust from a zoned date-time to UTC, extract a Instant.
Instant instant = zdt.toInstant() ;
And go back again.
ZonedDateTime zdt = instant.atZone( ZoneId.of( "Africa/Tunis" ) ) ;
LocalDateTime
A couple of other Answers use the LocalDateTime class. That class in not appropriate to the purpose of tracking actual moments, specific moments on the timeline, as it intentionally lacks any concept of time zone or offset-from-UTC.
So what is LocalDateTime good for? Use LocalDateTime when you intend to apply a date & time to any locality or all localities, rather than one specific locality.
For example, Christmas this year starts at the LocalDateTime.parse( "2018-12-25T00:00:00" ). That value has no meaning until you apply a time zone (a ZoneId) to get a ZonedDateTime. Christmas happens first in Kiribati, then later in New Zealand and far east Asia. Hours later Christmas starts in India. More hour later in Africa & Europe. And still not Xmas in the Americas until several hours later. Christmas starting in any one place should be represented with ZonedDateTime. Christmas everywhere is represented with a LocalDateTime.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
With Java 8 and later, use the java.time package.
ZonedDateTime.now().getYear();
ZonedDateTime.now().getMonthValue();
ZonedDateTime.now().getDayOfMonth();
ZonedDateTime.now().getHour();
ZonedDateTime.now().getMinute();
ZonedDateTime.now().getSecond();
ZonedDateTime.now() is a static method returning the current date-time from the system clock in the default time-zone. All the get methods return an int value.
Or use java.sql.Timestamp. Calendar is kinda heavy,I would recommend against using it
in production code. Joda is better.
import java.sql.Timestamp;
public class DateTest {
/**
* #param args
*/
public static void main(String[] args) {
System.out.println(new Timestamp(System.currentTimeMillis()));
}
}
in java 7 Calendar one line
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").format(Calendar.getInstance().getTime())
Use the formatting pattern 'dd-MM-yyyy HH:mm:ss aa' to get date as 21-10-2020 20:53:42 pm
Look at the API documentation for the java.util.Calendar class and its derivatives (you may be specifically interested in the GregorianCalendar class).
Calendar now = new Calendar() // or new GregorianCalendar(), or whatever flavor you need
now.MONTH
now.HOUR
etc.

In Joda-Time, set DateTime to start of month

My API allows library client to pass Date:
method(java.util.Date date)
Working with Joda-Time, from this date I would like to extract the month and iterate over all days this month contains.
Now, the passed date is usually new Date() - meaning current instant. My problem actually is setting the new DateMidnight(jdkDate) instance to be at the start of the month.
Could someone please demonstrates this use case with Joda-Time?
Midnight at the start of the first day of the current month is given by:
// first midnight in this month
DateMidnight first = new DateMidnight().withDayOfMonth(1);
// last midnight in this month
DateMidnight last = first.plusMonths(1).minusDays(1);
If starting from a java.util.Date, a different DateMidnight constructor is used:
// first midnight in java.util.Date's month
DateMidnight first = new DateMidnight( date ).withDayOfMonth(1);
Joda Time java doc - https://www.joda.org/joda-time/apidocs/overview-summary.html
An alternative way (without taking DateMidnight into account) to get the first day of the month would be to use:
DateTime firstDayOfMonth = new DateTime().dayOfMonth().withMinimumValue();
First Moment Of The Day
The answer by ngeek is correct, but fails to put the time to the first moment of the day. To adjust the time, append a call to withTimeAtStartOfDay.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
org.joda.time.DateTime startOfThisMonth = new org.joda.time.DateTime().dayOfMonth().withMinimumValue().withTimeAtStartOfDay();
org.joda.time.DateTime startofNextMonth = startOfThisMonth.plusMonths( 1 ).dayOfMonth().withMinimumValue().withTimeAtStartOfDay();
System.out.println( "startOfThisMonth: " + startOfThisMonth );
System.out.println( "startofNextMonth: " + startofNextMonth );
When run in Seattle US…
startOfThisMonth: 2013-11-01T00:00:00.000-07:00
startofNextMonth: 2013-12-01T00:00:00.000-08:00
Note the difference in those two lines of console output: -7 vs -8 because of Daylight Saving Time.
Generally one should always specify the time zone rather than rely on default. Omitted here for simplicity. One should add a line like this, and pass the time zone object to the constructors used in example above.
// Time Zone list: http://joda-time.sourceforge.net/timezones.html (Possibly out-dated, read note on that page)
// UTC time zone (no offset) has a constant, so no need to construct: org.joda.time.DateTimeZone.UTC
org.joda.time.DateTimeZone kolkataTimeZone = org.joda.time.DateTimeZone.forID( "Asia/Kolkata" );
java.time
The above is correct but outdated. The Joda-Time library is now supplanted by the java.time framework built into Java 8 and later.
The LocalDate represents a date-only value without time-of-day and without time zone. A time zone is crucial in determine a date. For any given moment the date varies by zone around the globe.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );
Use one of the TemporalAdjusters to get first of month.
LocalDate firstOfMonth = today.with( TemporalAdjusters.firstDayOfMonth() );
The LocalDate can generate a ZonedDateTime that represents the first moment of the day.
ZonedDateTime firstMomentOfCurrentMonth = firstOfMonth.atStartOfDay( zoneId );
Oh, I did not see that this was about jodatime. Anyway:
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
int min = c.getActualMinimum(Calendar.DAY_OF_MONTH);
int max = c.getActualMaximum(Calendar.DAY_OF_MONTH);
for (int i = min; i <= max; i++) {
c.set(Calendar.DAY_OF_MONTH, i);
System.out.println(c.getTime());
}
Or using commons-lang:
Date min = DateUtils.truncate(date, Calendar.MONTH);
Date max = DateUtils.addMonths(min, 1);
for (Date cur = min; cur.before(max); cur = DateUtils.addDays(cur, 1)) {
System.out.println(cur);
}
DateMidnight is now deprecated. Instead you can do:
LocalDate firstOfMonth = new LocalDate(date).withDayOfMonth(1);
LocalDate lastOfMonth = firstOfMonth.plusMonths(1).minusDays(1);
If you know the time zone use new LocalDate(date, timeZone) instead for greater accuracy.
You can also do .dayOfMonth().withMinimumValue() instead of .withDayOfMonth(1)
EDIT:
This will give you 12/1/YYYY 00:00 and 12/31/YYYY 00:00. If you rather the last of the month be actually the first of the next month (because you are doing a between clause), then remove the minusDays(1) from the lastOfMonth calculation
You can get Start date and end date of month using this:
DateTime monthStartDate = new DateTime().dayOfMonth().withMinimumValue();
DateTime monthEndDate = new DateTime().dayOfMonth().withMaximumValue();

Categories