How to get year, month, day in UTC? - java

I have a some Date that was gotten by Calendar.getInstance() (in local time zone as I got).
public final class Converter {
private static final TimeZone UTC_ZONE = TimeZone.getTimeZone("UTC");
private Converter() {
}
public static int toPackedUTCDate(Date date) {
Calendar c = Calendar.getInstance(UTC_ZONE);
c.setTime(date);
int year = c.get(Calendar.YEAR); // UTC year
int month = c.get(Calendar.MONTH); // UTC month
int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); // UTC day of month
return TimeUtils.packDate(dayOfMonth, month, year);
}
}
Of course, it's a wrong code but how to get a correct? Cuz date was gotten by Calendar.getInstance().getTime(). Sorry, I really can't get all these time zones... If someone can explain me clearly I will be very grateful. I just need to the user could input his date (in his local time zone) and my app has stored as date in UTC in own packed format.

tl;dr
LocalDate.now( ZoneOffset.UTC )
java.time
You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
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.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, 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" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
If you want UTC, use the constant defined as ZoneOffset.UTC.
LocalDate todayUtc= LocalDate.now( ZoneOffset.UTC ) ;
Sorry, I really can't get all these time zones
These concepts have been covered many many times already on Stack Overflow, sometimes quite in-depth.
Search thoroughly before posting. Search for Instant, ZoneId, ZoneOffset, "java.time", OffsetDateTime, ZonedDateTime, DateTimeFormatter.
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.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, 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, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

Date date = new Date(year,month,day,hour,min);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date utc= new Date(sdf.format(date));

Related

Get the First day and the last day of month from an Instant

I have a method using 2 Instants in parameters getIssuesBillable(Instant start, Instant end, ....), my question is how I get the first day of a month and the last day of the month using a Java 8 Instant?
I already tried use withDayOfMonth(), and lengthOfMonth():
LocalDate initial = LocalDate.now();
LocalDate start = initial.withDayOfMonth(firstDayOfMonth());
LocalDate end = initial.withDayOfMonth(lastDayOfMonth());
But in this case, I need to convert and make some workarounds in this case, if someone knows a better way to do it I really appreciate any response.
tl;dr
Use modern java.time classes.
Here is a brief nonsensical example of starting with an Instant (a moment in UTC), assigning a time zone to view that moment through the wall-clock time used by the people of a particular region (a time zone), extracting the year-and-month as perceived in that time zone, and determining the first and last day of that month, rendering LocalDate objects.
YearMonth // Represent a year-and-month, the entire month as a whole.
.from( // Determine the year-and-month of some other date-time object.
Instant // Represent a moment in UTC.
.now() // Capture the current moment in UTC.
.atZone( // Adjust from UTC to a particular time zone.
ZoneId.of( "Pacific/Auckland" )
) // Returns a `ZonedDateTime` object.
) // Returns a `YearMonth` object.
.atDay( 1 ) // Returns a `LocalDate` object.
…or
…
.atEndOfMonth() // Returns a `LocalDate` object.
By the way, a realistic version of that particular code would be: YearMonth.now( ZoneId.of( "Pacific/Auckland" ) ).atDay( 1 )
Moment versus date-only
Instant is a moment in UTC, a date with time-of-day and an offset-from-UTC of zero.
A LocalDate is a date-only value, without time-of-day and without time zone.
You need to specify the time zone by which you want to perceive the date, the wall-clock time used by the people of a particular region.
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( "Africa/Casablanca" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Extract the date-only.
LocalDate ld = zdt.toLocalDate() ;
From there, proceed with your other code.
Or work with the month as a whole, using YearMonth class.
YearMonth ym = YearMonth.from( zdt ) ;
LocalDate first = ym.atDay( 1 ) ;
LocalDate last = ym.atEndOfMonth() ;
Tip: You might find helpful the LocalDateRange and Interval classes in the ThreeTen-Extra library.
Tip: Learn about the Half-Open approach to define a span of time, where the beginning is inclusive while the ending is exclusive. So a month starts on the first and runs up to, but does not include, the first day of the following month.
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, Java SE 11, and later - 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
Most 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….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
For the first day of the month, depends on the time zone:
YearMonth.from(Instant.now().atZone(ZoneId.of("UTC"))).atDay(1);
For the last day of the month, depends on the time zone:
YearMonth.from(Instant.now().atZone(ZoneId.of("UTC"))).atEndOfMonth();

Java Convert UTC Date to local Date with Joda

This code is working, but I want to use Joda-Time
public static Date dateFromUTC(Date date){
return new Date(date.getTime() + Calendar.getInstance().getTimeZone().getOffset(date.getTime()));
}
I tried this, but it's not working - what's the problem with this?
public static Date dateFromUTC(Date date){
return new DateTime(date).withZone(DateTimeZone.getDefault()).toDate();
}
tl;dr
Use java.time classes instead.
Instant.now() // Capture current moment in UTC. Always in UTC, by definition.
…and…
ZonedDateTime.now() // Capture current moment as seen through the wall-clock time of the people in the region of the time zone used by default in this JVM.
Details
As others said, you misunderstood the concepts involved in these classes. A java.util.Date represents a moment in UTC, always in UTC†, never in some other time zone. So the code seen in the Question is non-sensical. You are working too hard!
java.time
The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. Many of the concepts are similar between Joda-Time and java.time as both projects are led by the same man, Stephen Colebourne.
When you are ready to migrate, use Instant in place of java.util.Date.
Instant instant = Instant.now() ; // Capture the current moment in UTC.
instant.toString(): 2018-01-23T12:34:56.123456789Z
Instead of java.util.Calendar, use ZonedDateTime to represent a moment seen through the wall-clock time of a particular region (a time zone).
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( "Pacific/Auckland" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same moment, same point on the timeline, different wall-clock time.
As a shortcut, you can skip the Instant if you want only the zoned time.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ; // Capture the current moment as seen by people in a certain time zone.
You can get to UTC from there by extracting an Instant object.
Instant instant = zdt.toInstant() ; // Same moment, same point on the timeline, but viewed with the wall-clock time of UTC.
† Actually, there is a time zone assigned deep within a java.util.Date but is irrelevant to our discussion here. Confusing? Yes. One of many reasons to avoid the awful mess that is the old Date/Calendar and related legacy date-time classes.
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….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Try this:
new DateTime(date, DateTimeZone.UTC)
.toLocalDateTime() // value without timezone
.toDateTime() // convert to default timezone
.toDate();
Your code actually does nothing to the date, because new DateTime(date) creates a DateTime object with default timezone. And then you just convert it back to java.util.Date.
First of all, read the article linked in the comments: https://codeblog.jonskeet.uk/2017/04/23/all-about-java-util-date/
A java.util.Date doesn't have a timezone. It actually represents a point in time: the number of milliseconds since unix epoch (Jan 1st 1970, at midnight, in UTC).
When you print the Date, though, it uses the JVM default timezone to convert the Date to date/time values, but the Date itself doesn't have a timezone.
That's why converting a Date object to another timezone doesn't make sense.
If you want to know the date (day, month, year) and time (hour, minute, second, millisecond) that corresponds to the Date in a specific timezone, then you can use Joda-Time:
// java.util.Date
Date date = new Date();
// the Date converted to UTC
DateTime utc = new DateTime(date, DateTimeZone.UTC);
// the Date converted to JVM default timezone
DateTime convertedToDefaultTz= new DateTime(date, DateTimeZone.getDefault());
The conversion can also be made using another DateTime:
DateTime convertedToDefaultTz = utc.withZone(DateTimeZone.getDefault());
Joda's DateTime has a timezone attached to it, so now it makes sense to convert to another one. But the Date objects returned by it will always be the same, because all of them represent the same instant (the same point in the timeline):
Date d1 = utc.toDate();
Date d2 = convertedToDefaultTz.toDate();
System.out.println(d1.equals(d2)); // true
All because - again - a Date doesn't have a timezone.

SetDate() to Calendar object to change time, changes the date back to 1970

So, I start getting the current time in a Calendar object named startTime
Calendar startTime = Calendar.getInstance();
Log.w(TAG, "CALENDAR BEFORE: " + startTime.getTime());
This works great, as my logs say that the time is the current one (i.e. Tue Nov 07 12:50:10 CST 2017).
However I need to get a time from a Preference option, which returns me something like this: "15:00". This is being stored in a String alarmPref
String alarmPref = preferences.getString(keyAlarm, "12:00");
Log.w(TAG, "AlarmReceiver: Alarm going to be set at: " + alarmPref);
Here is where it gets tricky, I change this String to a Date using a SimpleDateFormat with only hours and minutes (adding date stuff crashes).
SimpleDateFormat format = new SimpleDateFormat("HH:mm", Locale.getDefault());
And when I try to add this time to the Calendar object I created first (startTime) it changes the time to "Thu Jan 01 15:00:00 CST 1970", where I have the correct time but not date.
Date newDate = format.parse(alarmPref);
startTime.setTime(newDate);
Log.w(TAG, "CALENDAR AFTER SET: " + startTime.getTime());
I've been trying to fix this but haven't found the solution, nor similar problems.
If your goal is to alter a date-time by setting a specific time-of-day…
tl;dr
ZonedDateTime.of(
LocalDate.now( ZoneId.of( "America/Chicago" ) ) , // Get the current date for a particular place on Earth.
LocalTime.parse( "15:00" ) , // Specify the time-of-day.
ZoneId.of( "America/Chicago" ) // Assign the intended zone to the resulting `ZonedDateTime` object.
)
Issue
You are parsing a String representing a time-of-day as a date-time value. That parsing method assumes you want the first day since the epoch reference date of 1970-01-01T00:00:00Z. So you got 3 PM on January 1st of 1970. That is all correct documented behavior. But not what you intended.
Solution
Avoid legacy classes
Avoid the troublesome old date-time classes bundled with the earliest versions of Java such as Calendar. These were supplanted years ago in Java 8 and Java 9 by the java.time classes. For earlier Android, see the last bullets below.
Time zone
Specify your intended time zone. If omitted, the JVM’s current default time zone is implicitly applied. That default may change at any moment during runtime, and so is unreliable.
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 CST or EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Chicago" ) ;
A time zone is crucial in determining a date and time-of-day. 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.
ZonedDateTime zdtNow = ZonedDateTime.now( z ) ;
Time-of-day
For a time-of-day only value, without any date and without an time zone, use the LocalTime class.
LocalTime lt = LocalTime.parse( "15:00" ) ;
Date-only + Time-of-Day
You want the same date but with another time-of-day. So extract the date-only portion, combine with the desired time-of-day while applying the intended time zone to get a new ZonedDateTime object.
LocalDate ld = zdtNow.toLocalDate() ;
ZonedDateTime zdtTodayAtThreePm = ZonedDateTime.of( ld , lt , z ) ;
Tip: Generally best to do your logging, serializing, and data exchange in UTC rather than a particular time zone. For that use the Instant class. You can extract a Instant from a ZonedDateTime.
Instant instant = zdtTodayAtThreePm.toInstant() ; // Always in UTC.
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….
I managed to get a fixed by doing this:
String alarmPref = preferences.getString(keyAlarm, "12:00");
Log.w(TAG, "AlarmReceiver: Alarm going to be set at: " + alarmPref);
SimpleDateFormat format = new SimpleDateFormat("HH:mm", Locale.getDefault());
Date newDate = format.parse(alarmPref);
//startTime.setTime(newDate);
startTime.set(Calendar.HOUR_OF_DAY, newDate.getHours());
startTime.set(Calendar.MINUTE, newDate..getHours());
startTime.set(Calendar.SECOND, 0);
Log.w(TAG, "CALENDAR AFTER SET: " + startTime.getTime());
Where I only set the HOURS and MINUTES (and seconds to 0), and the date remains the same. However the methods .getHours() and .getHours() are deprecated, is there a more fancy way to do this?
I don't see any problems here. You are asking the SimpleDateFormat to parse a Date, by only providing hours and minutes. It defaults the other fields which are missing from your input to the beginning of time, which is not what you expect. Apparently the developer who implemented SimpleDateFormat thought that this behavior is reasonable.
The workaround in which you set only the HOUR_OF_DAY and MINUTE looks good.

How to get the current time in your timezone in Java

I have no idea why Java makes it near impossible to do such a simple thing. I have tried many solutions I find online, but there doesn't seem to be a simple clean and working solution.
Here is my latest attempt at a solution
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles"));
System.out.println( sdf.format(calendar.getTime()) );
My excepted output: 27/02/2014 17:06:00
My real output: 03/03/2014 20:35:44
How does this even make any sense.
set timezone in SimpleDateFormat instance instead
sdf.setTimezone("America/Los_Angeles");
tl;dr
ZonedDateTime.now()
Details
The real problem is using the notoriously troublesome java.util.Date and .Calendar classes. Use the modern java.time classes instead.
java.time
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, 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/Los_Angeles" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ; // Capture the current moment, with wall-clock time used by people of a particular region.
See this code run live at IdeOne.com.
zdt.toString(): 2018-01-28T15:12:58.942-08:00[America/Los_Angeles]
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
To generate strings in other formats, search Stack Overflow for DateTimeFormatter.
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.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, 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, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
Joda-Time
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. Leaving this section for history.
One important difference is that while a java.util.Date has no timezone, a DateTime (in Joda-Time) and a ZonedDateTime (in java.time) both truly know their own assigned time zone.
Example code in Joda-Time 2.3. If you choose to not specify a time zone, you get the JVM's default time zone. Use proper time zone names, never the 3 or 4 letter codes.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime now = new DateTime( timeZone );
DateTime nowDefaultTimeZone = new DateTime();
String output is in ISO 8601 format (ex: 2014-02-27T23:03:14+3:00) by default. To create string representations in other formats, search StackOverflow for "joda format".
SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
System.out.println(sdf.format(new Date()));
TimeZone timeZone=TimeZone.getDefault();
System.out.println(timeZone.getDisplayName());
TimeZone americaTimeZone=TimeZone.getTimeZone("America/Los_Angeles");
sdf.setTimeZone(americaTimeZone);
Calendar calendar=Calendar.getInstance(americaTimeZone);
System.out.println(sdf.format(calendar.getTime()));
SimpleDateFormat default format with default TimeZone;
After hours DuckDuckGoging I solved it in Android with (the call requires API level 24):
Calendar calendario = Calendar.getInstance(TimeZone.getTimeZone(Time.getCurrentTimezone()));

How to get Java to show the day of month from a date?

I am trying to extract the day of month of today's date. I have this
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
JOptionPane.showMessageDialog(null, date.getDay());
but when the message dialog appears it show the number 5
and today it's the 8th. How can I set it to show what day of the month it is?
date.getDay() returns the day of the week. sunday is 0 and similarly saturday is 6.
Please see the java docs
As per the comment given below
Calendar cal = Calendar.getInstance();
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
String dayOfMonthStr = String.valueOf(dayOfMonth);
System.out.println(dayOfMonthStr);
Try this out.
JOptionPane.showMessageDialog(null, date.getTime());
You started to use the SimpleDateFormat class, but didn't do anything with it. Try:
System.out.println( new SimpleDateFormat("EEEE").format( new Date() ) );
System.out.println( new SimpleDateFormat("d").format( new Date() ) );
tl;dr
LocalDate.now() // Capture the current date as seen in the wall-clock time used by the people of a certain region, that region represented by the JVM’s current default time zone.
.getDayOfMonth() // Extract the day-of-month. Returns an `int`.
java.time
extract the day of month of today's date
The modern approach uses the java.time classes that supplant the troublesome old date-time classes bundled with the earliest versions of Java.
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.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, 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" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Interrogate the LocalDate for its day-of-month.
int dayOfMonth = today.getDayOfMonth() ;
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….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Joda-Time
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. I am leaving this section intact as history.
In Joda-Time 2.3 in Java 7…
org.joda.time.DateTime theEighth = new org.joda.time.DateTime( 2013, 11, 8, 18, 0 ); // Default time zone.
System.out.println( "theEighth: " + theEighth );
System.out.println( "dayOfMonth of theEighth: " + theEighth.dayOfMonth().getAsText() );
When run…
theEighth: 2013-11-08T18:00:00.000-08:00
dayOfMonth of theEighth: 8

Categories

Resources