I want to parse a date in YYYY-MM-DD format to YYYYMMDD. If I use the following function, it returns me a YYYYMMDD format but with a different DD. i.E: 2013-05-16 BECOMES 20130515
Apologies for sounding illiterate :) I am new to Java.
Any help would be appreciated.
String TestDate=yyyymmddParser.format(oLifEExtension.TestDate().getTime());
sb.append(TestDate)
Not sure if the Question was meant for java.util.Date (a date plus time-of-day) or a java.sql.Date (a date-only). In both cases, you should be using the modern java.time classes rather than the troublesome legacy date-time classes.
Some other java.sql.Date questions are linked as duplicates of this one. So I handle both classes (sql & util) here.
java.util.Date
The legacy java.util.Date class represents a moment on the timeline in UTC. This means a date with a time-of-day. The trick is that your input string is for a date-only value. You can first parse your string as a date-only value, then assign a time-of-day if desired.
Your input string complies with the standard ISO 8601 format of YYYY-MM-DD. The java.time classes default to the standard formats when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate ld = LocalDate.parse( "2013-05-16" ) ;
For a time-of-day, you probably want the first moment of the day. Do not assume the first moment is 00:00:00. In some time zones an anomaly such as Daylight Saving Time (DST) may cause a day to start at a different time such as 01:00:00. To account for such anomalies, we must specify a time zone in determining the first moment of the day.
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" ) ;
Apply that zone in asking java.time to determine the first moment of the day. We produce a ZonedDateTime object as the result.
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
If you desire a specific time of day, apply a LocalTime object. Keep in mind that your time-of-day may not be valid on that particular date for that particular zone. For example, you may be specifying a time-of-day occurring during a DST cutover. In such a case, the ZonedDateTime class has a policy for adjusting to accommodate. Be sure to read the documentation to understand that policy and the resulting behavior.
LocalTime lt = LocalTime.of( 12 , 0 ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ; // Time-of-day may be adjusted as needed.
java.sql.Date
No need to use java.sql.Date. That class is replaced by LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.
JDBC drivers that comply with JDBC 4.2 can deal directly with java.time types by calling:
PreparedStatement::setObjectmyPrepStmt.setObject( … , myLocalDate ) ;
ResultSet::getObjectLocalDate ld = myResultSet.getObject( … , LocalDate.class );
For presentation of the LocalDate to the user, generate a String for display in your user-interface. Use a DateTimeFormatter to automatically localize. To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
Example:
Locale l = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( l );
String output = zdt.format( f );
You can go the other direction as well, parsing an input string to get a date.
LocalDate ld = LocalDate.parse( input , f ) ;
Trap for the exception thrown if the user’s input is faulty or unexpected.
try{
LocalDate ld = LocalDate.parse( input , f ) ;
myPrepStmt.setObject( … , ld ) ;
} catch ( DateTimeParseException e ) {
… // Handle the error condition of faulty/unexpected input by user.
}
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
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
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.
A SimpleDateFormat should be capable of achieving what you're after. Be very careful with the format marks, D and d mean different things
String oldDateString = "2013-05-16";
System.out.println(oldDateString );
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(oldDateString);
System.out.println(date);
String newDateString = new SimpleDateFormat("yyyyMMdd").format(date);
System.out.println(newDateString);
(Also, beware of Y and y :P)
This outputs
2013-05-16
Thu May 16 00:00:00 EST 2013
20130516
For me...
Related
I am very new to OffsetDateTime usage and I am trying to compare OffsetDateTime strings with OffsetDateTime.now() in java this way,
import java.time.OffsetDateTime;
public class OffsetDateTimeDemo {
public static void main(String[] args) {
OffsetDateTime one = OffsetDateTime.parse("2017-02-03T12:30:30+01:00");
System.out.println("First ::" + OffsetDateTime.now().compareTo(one));
OffsetDateTime date1 = OffsetDateTime.parse("2019-02-14T00:00:00");
System.out.println("Second ::" + OffsetDateTime.now().compareTo(date1));
OffsetDateTime date3 = OffsetDateTime.parse("Mon Jun 18 00:00:00 IST 2012");
System.out.println(" Third :: " +OffsetDateTime.now().compareTo(date3));
}
}
But I am getting java.time.format.DateTimeParseException in all the 3 cases.
However if i compare 2 OffsetDateTime Strings with CompareTo method its working fine.
Can someone shed some light to me in this regard and kindly guide me through my mistake.
Thanks in Advance.
Your compareTo coding is a distraction. Your exception is about parsing the string inputs into objects.
Another problem: You are using wrong classes on the 2nd and 3rd inputs.
Another problem: You are relying implicitly on your JVM’s current default time zone when calling now(). Poor practice as any programmer reading will not know if you intended the default or if you were unaware of the issue as are so many programmers. Furthermore, the current default can be changed at any moment during runtime by any code in any thread of any app within the JVM. So better to always specify explicitly your desired/expected zone or offset.
OffsetDateTime.now(
ZoneOffset.UTC
)
Or better yet, use a ZonedDateTime to capture more information than a OffsetDateTime.
ZonedDateTime.now(
ZoneId.of( "Pacific/Auckland" )
)
First: OffsetDateTime works
Your first string input is proper, and parses successfully.
OffsetDateTime.parse( "2017-02-03T12:30:30+01:00" )
Full line of code:
OffsetDateTime odt = OffsetDateTime.parse( "2017-02-03T12:30:30+01:00" ) ;
See this code run live at IdeOne.com.
odt.toString(): 2017-02-03T12:30:30+01:00
To compare, extract an Instant. Doing so effectively adjusts your moment from some offset to an offset of zero, or UTC itself. An Instant is always in UTC, by definition.
Instant instant = Instant.now() ; // Capture the current moment as seen in UTC.
boolean odtIsPast = odt.toInstant().isBefore( instant ) ;
Second: LocalDateTime
Your second string input lacks any indicator of offset-from-UTC or time zone. So an OffsetDateTime is the wrong class to use. Instead use LocalDateTime which lacks any concept of offset or zone.
This means a LocalDateTime cannot represent a moment. For example, noon on the 23rd of January this year could mean noon on Asia/Tokyo which would be hours earlier than noon in Europe/Paris, or it could mean noon in America/Montreal which would be a moment even more hours later. Without the context of a zone or offset, a LocalDateTime has no real meaning. So comparing a LocalDateTime to the current moment is senseless.
LocalDateTime.parse( "2019-02-14T00:00:00" )
See this code run live at IdeOne.com.
ldt.toString(): 2019-02-14T00:00
To compare, you can’t — illogical as discussed above. You must assign a time zone (or offset) to determine a moment on the timeline. If you know for certain this date and time were meant for a specific time zone, assign ZoneId to get a ZonedDateTime. Then extract a Instant to compare.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ; // India time.
ZonedDateTime zdt = ldt.atZone( z ) ;
Instant instant = Instant.now() ; // Capture the current moment as seen in UTC.
boolean zdtIsPast = zdt.toInstant().isBefore( instant ) ; // Compare.
By the way, I noticed the time-of-day is zero. If your goal was to represent the date only, without any time-of-day and without any zone, use LocalDate class.
Third: Don’t bother, ambiguous input
Your third string input carries a time zone indicator. So it should be parsed as a ZonedDateTime.
Unfortunately, you’ve chosen a terrible string format to parse. Never use the 2-4 character pseudo-zones like IST. They are not standardized. And they are not unique! Your IST could mean Ireland Standard Time or India Standard Time or others.
Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
See this code run live at IdeOne.com.
zdt.toString(): 2019-02-20T22:34:26.833+01:00[Africa/Tunis]
You could try to parse this. ZonedDateTime will make a guess as to which zone was meant by IST. But it would be just a guess, and so is unreliable given the inherently ambiguous input. Personally, I would refuse to code that, rejecting this input data back to its source.
If you insist on making this unreliable parse attempt, see the correct Answer to a similar Question you asked recently.
Educate your source about always using standard ISO 8601 formats to exchange date-time values as human-readable text.
The java.time classes use these ISO 8601 formats by default when parsing/generating strings. The ZonedDateTime class wisely extends the standard to append the standard name of the time zone in square brackets.
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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.
I have method to find month end date based on the timezone.
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("CET"));
calendar.set(
Calendar.DAY_OF_MONTH,
calendar.getActualMaximum(Calendar.DAY_OF_MONTH)
);
System.out.println(calendar.getTime());`
It displays output: Thu Aug 30 18:04:54 PDT 2018.
It should, however, give me an output in CET.
What am I missing?
The Calendar.getTime() method returns a Date object, which you then printed in your code. The problem is that the Date class does not contain any notion of a timezone even though you had specified a timezone with the Calendar.getInstance() call. Yes, that is indeed confusing.
Thus, in order to print a Date object in a specific timezone, you have to use the SimpleDateFormat class, where you must call SimpleDateFormat.setTimeZone() to specify the timezone before you print.
Here's an example:
import java.util.Calendar;
import java.util.TimeZone;
import java.text.SimpleDateFormat;
public class TimeZoneTest {
public static void main(String argv[]){
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("CET"));
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
System.out.println("calendar.getTime(): " + calendar.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone("CET"));
System.out.println("sdf.format(): " + sdf.format(calendar.getTime()));
}
}
Here is the output on my computer:
calendar.getTime(): Fri Aug 31 01:40:17 UTC 2018
sdf.format(): 2018-Aug-31 03:40:17 CEST
This is because Date object doesn't have timezone as part of its state, and getTime() actually returns a date which corresponds to the JVM's timezone, instead you need SimpleDateFormat to format and print the date in your required timezone.
If you try adding the following line of code, you could see that the timezone in the calendar is actually CET.
System.out.println(calendar.getTimeZone().getDisplayName());
tl;dr
YearMonth // Represent a year-month without day-of-month.
.now( // Capture the current year-month as seen in the wall-clock time used by the people of a particular region (a time zone).
ZoneId.of( "Africa/Tunis" ) // Specify your desired time zone. Never use 3-4 letter pseudo-zones such as `CET`.
) // Returns a `YearMonth` object.
.atEndOfMonth() // Determine the last day of this year-month. Returns a `LocalDate` object.
.atStartOfDay( // Let java.time determine the first moment of the day. Not necessarily 00:00:00, could be 01:00:00 or some other time-of-day because of anomalies such as Daylight Saving Time (DST).
ZoneId.of( "Africa/Tunis" )
) // Returns a `ZonedDateTime` object, representing a date, a time-of-day, and a time zone.
java.time
You are using the terrible old Calendar class that was supplanted years ago but the modern java.time classes.
LocalDate
If you need only a date, use LocalDate class. Then the time zone is irrelevant for your output.
But time zone is very relevant for determining the current date. For any given moment, the date varies around the globe by 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 CET or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Europe/Paris" ) ; // Or "Africa/Tunis" etc.
LocalDate today = LocalDate.now( z ) ; // Capture the current date as seen by the wall-clock time used by the people of a certain region (a time zone).
YearMonth
Get the month for that date. Represent a year-month with, well, YearMonth.
YearMonth ym = YearMonth.from( today ) ;
Or skip the LocalDate.
YearMonth ym = YearMonth.now( z ) ;
Get the end of the month.
LocalDate endOfThisMonth = ym.atEndOfMonth() ;
ISO 8601
To generate a String representing that LocalDate object’s value, call toString. The default format is taken from the ISO 8601 standard. For a date-only value that will be YYYY-MM-DD such as 2018-01-23.
String output = endOfThisMonth.toString() ;
If you need another format, use DateTimeFormatter class. Search Stack Overflow for many examples and discussions.
Moment
If you need a moment, you can add a time-of-day and time zone to your LocalDate to get a ZonedDateTime. Or let ZonedDateTime determine the first moment of the day (which is not always 00:00:00!).
ZonedDateTime zdt = LocalDate.atStartOfDay( z ) ;
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.
Below is my code for formatting time
public class FormatTime {
public static void main(String[] args) throws Exception {
FormatTime ft = new FormatTime();
System.out.println(ft.evaluate("12/01/2014 05:30:15 PM","MM/dd/yyyy hh:mm:ss aa", "yyyy-MM-dd HH:mm:ss"));
}
public String evaluate(String time,String iFormat ,String f) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat(f);
SimpleDateFormat inFormat = new SimpleDateFormat(iFormat);
Date date=inFormat.parse(time);
String fechaNueva = format.format(date);
return fechaNueva;
}
}
Out put of this program is as expected that it give 2014-12-01 17:30:15.
But when I replace hh to HH in iFormat (same as in outputformat) then it give output in 12 out format 2014-12-01 05:30:15
Same also happens if I convert both in lower case that is hh. Why does this type of inconsistency occur?
I don't think it's inconsistent. When you evaluate the time using HH it will ignore the aa bit, as it's evaluating the input as a 24-hour time, and the aa bit makes no sense. However, when you run it with hh it will read 05:30:15 PM as "half five in the afternoon" and writing it will give 2014-12-01 17:30:15. Reading 05:30:15 PM as a 24-hour time, will read it as "half five in the morning", throwing the PM bit away.
When having both formats with hh, you're both reading and writing in 12 hour format. For at to make sense, you would need to add the aa bit to the output format as well.
I hope that answers your question in a way that makes sense :)
tl;dr
LocalDateTime.parse( // Parse as a date-time lacking time zone or offset-from-UTC.
"12/01/2014 05:30:15 PM" , // Define a formatting pattern to match input. Case-sensitive formatting code. Use `h` lowercase for 12-hour clock, 0-12. Use uppercase `H` for 24-hour clock, 0-23.
DateTimeFormatter.ofPattern( "MM/dd/uuuu hh:mm:ss a" , Locale.US )
).format( // Generate a String in specific format. Generally better to let java.time localize automatically.
DateTimeFormatter.ofPattern( "MM/dd/uuuu hh:mm:ss a" , Locale.US )
)
java.time
The modern approach uses java.time classes that supplanted the troublesome old date-time classes.
Get the current moment in UTC. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now() ;
To see that same moment through the lens of a wall-clock time used by people of a certain region (time zone), apply a ZoneId to get a ZonedDateTime.
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/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
To generate a string in standard ISO 8601 format on any of these, call toString. The java.time classes use standard formats by default when paring/generating strings. So no need to specify a formatting pattern.
If you want other formats, use the DateTimeFormatter or DateTimeFormatterBuilder classes. You can specify a formatting pattern, but easier to let java.time automatically localize.
To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
Example:
Locale l = Locale.FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( l );
String output = zdt.format( f );
mercredi 14 février 2018 à 00:59:07 heure normale d’Europe centrale
Or, Locale.US & FormatStyle.SHORT.
2/14/18, 1:01 AM
Your custom format for your input is:
String input = "12/01/2014 05:30:15 PM" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu hh:mm:ss a" , Locale.US ) ;
That input string lacks any indicator of a time zone or offset-from-UTC. So it is not a moment, not a specific point on the timeline. It represents a vague idea about potential moments along a range of about 26-27 hours. As such, we parse this input into a LocalDateTime lacking any concept of zone/offset.
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
ldt.toString(): 2014-12-01T17:30:15
Generate a string in that format.
String output = ldt.format( f ) ;
12/01/2014 05:30:15 PM
As others explained, the formatting codes are case-sensitive. If you want 24-hour time, use uppercase H. For 12-hour time, use lowercase h.
Note that the formatting codes in java.time are close to those of the legacy SimpleDateFormat but not exactly the same. Study the documentation and search Stack Overflow for many examples.
When exchanging date-time values as text, stick with the standard ISO 8601 formats.
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.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.
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….
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.
I have a string of the form "mm/yyyy" and I want to compare it against the date of the local system.
I have thought of either using a conversion table between my month and the MONTH field in Calendar, something like:
Calendar cal = Calendar.getInstance();
String date = "07/2014";
String month = date.subString(0, 2);
int monthToCompare;
if (month.equals("01"))
monthToCompare = cal.JANUARY;
if (month.equals("02"))
monthToCompare = cal.FEBRUARY;
...
And then comparing manually with an if. I don't like it because I think is way too long for such a simple operation.
The other option I've thought of is getting the current Date() and using the before() method. That would mean translating my date to the Date format, but the easy methods to do it are deprecated, I must specify the number of milliseconds and I do not know how to easily do that (taking into consideration leap years, calendar corrections and so on since 1970).
Using #Mifmif answer I finally solved the problem with:
if (new SimpleDateFormat("MM/yyyy").parse(date).before(new Date())) {
...
}
Try this :
new SimpleDateFormat("MM/yyyy").parse("07/2014").compareTo(new Date());
tl;dr
YearMonth.parse(
"07/2014" ,
DateTimeFormatter.ofPattern( "MM/uuuu" )
).isAfter(
YearMonth.now(
ZoneId.of( "Africa/Tunis" )
)
)
java.time
The modern solution uses the java.time classes rather than the troublesome old date-time classes.
Year & month only
To represent an entire month, use the YearMonth class.
String input = "07/2014" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/uuuu" ) ;
YearMonth ym = YearMonth.parse( input , f ) ;
Tips: Use such YearMonth objects throughout your codebase rather than a mere string. And when you do need a string to exchange data, use standard ISO 8601 format: YYYY-MM. The java.time classes use standard formats by default when parsing/generating strings, so no need to define formatting pattern.
Current year-month
Determining the current year-month means determining the current date.
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.
Same idea applies to getting the current YearMonth: pass a ZoneId.
YearMonth currentYearMonth = YearMonth.now( z ) ;
Compare
Compare using methods isBefore, isAfter, and equals.
boolean isAfterCurrentYearMonth = ym.isAfter( currentYearMonth ) ;
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….
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.
//getting current date
private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
//compare the dates
Date date1 = new Date("second_date to be compared");
Date date2 = new Date(getDateTime());
if(date1.before(date2)) {
Log.d("Date already passed", " " + "second_date");
}
I declared Calendar and SimpleDateFormat like this:
calendar = Calendar.getInstance(TimeZone.getTimeZone("Malaysia"));
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MMMMM.dd hh:mm aaa");
or:
calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));
Then I call this:
sdf.format(calendar.getTime());
but result is not in correct time zone (+8 hours). What could be the problem?
Unless you are going to perform Date/Time related calculations, there is no point in instantiating Calendar with given TimeZone. After calling Calendar's getTime() method, you will receive Date object, which is timezone-less either way (GMT based, actually).
What you need to do, is to set TimeZone for formatter instead. And also do not bother with passing your own format, there is a built-in already:
// get current time
// you could just as well use Date now = new Date();
Calendar now = Calendar.getInstance();
// Locale for formatter
Locale malaysianLocale = new Locale("ms", "MY");
// Default date and time format for Malaysia
DateFormat defaultMalaysianFormatter = DateFormat.getDateTimeInstance(
DateFormat.DEFAULT, DateFormat.DEFAULT, malaysianLocale);
// This step is crucial
TimeZone malaysianTimeZone = TimeZone.getTimeZone("Asia/Kuala_Lumpur");
defaultMalaysianFormatter.setTimeZone(malaysianTimeZone);
System.out.println(defaultMalaysianFormatter.format(now.getTime()));
This prints something like 10 Mei 2011 2:30:05 AM, which I believe is your desired result.
Time zone id should be set as Asia/Kuala_Lumpur. Date.toString() always returns time string using default time zone. But your default time zone is different.
Calendar tzCal = Calendar.getInstance(TimeZone.getTimeZone("Asia/Kuala_Lumpur"));
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, tzCal.get(Calendar.YEAR));
cal.set(Calendar.MONTH, tzCal.get(Calendar.MONTH));
cal.set(Calendar.DAY_OF_MONTH, tzCal.get(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, tzCal.get(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, tzCal.get(Calendar.MINUTE));
cal.set(Calendar.SECOND, tzCal.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, tzCal.get(Calendar.MILLISECOND));
System.out.println("Current Time = " + sdf.format(cal.getTime()));
The TimeZone.getTimeZone() call is incorrect. You have to pass a the correct identifier.
EDIT -- You can try to getAvailableIDs() and iterate through them to make sure you have the correct id.
If you've read the javadoc of TimeZone carefully, the way to use getTimeZone is:
TimeZone.getTimeZone("GMT-8")
or
TimeZone.getTimeZone("GMT+8")
tl;dr
java.time.ZonedDateTime.now(
ZoneId.of( "Asia/Kuala_Lumpur" )
).toString()
2018-01-23T18:48:32.263+08:00[Asia/Kuala_Lumpur]
Avoid legacy classes
The Question and other Answers use troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
java.time
The modern approach uses java.time classes. Forget all about the terribly confusing Calendar class.
Current moment
First get the current moment in UTC. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now() ;
Time zone
Adjust into another 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 pseudo-zones such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Asia/Kuala_Lumpur" ) ; // Or "Asia/Kuching", etc.
Apply the ZoneId to instantiate a ZonedDateTime object. Both the ZonedDateTime and Instant represent the same moment, the very same point on the timeline, but is viewed through a different wall-clock time.
ZonedDateTime zdt = instant.atZone( z ) ; // Same moment, different wall-clock time.
Offset
If you had only an offset-from-UTC such as +08:00 rather than a known time zone, you would use ZoneOffset to get a OffsetDateTime instead of a ZoneId & ZonedDateTime. But a time zone is always preferable to a mere offset. A zone is a history of offsets used by the people of particular region.
Strings
To generate a string in standard ISO 8601 format, call toString method.
The ZonedDateTime class wisely extends the standard by appending the time zone name in square brackets.
String output = zdt.toString() ; // YYYY-MM-DDTHH:MM:SS.SSSSSSSSS[tz]
Localize to the user’s preferences. To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
Locale l = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( l );
String output = zdt.format( f );
Dump to console.
System.out.println( "instant.toString(): " + instant ) ;
System.out.println( "output: " + output ) ;
System.out.println( "outputLocalized (always Locale.US on IdeOne.com): " + outputLocalized ) ;
See this code run live at IdeOne.com. Note that IdeOne.com overrides any Locale setting to always use Locale.US.
instant.toString(): 2018-01-23T10:48:32.263Z
output: 2018-01-23T18:48:32.263+08:00[Asia/Kuala_Lumpur]
ooutputLocalized (always Locale.US on IdeOne.com): Tuesday, January 23, 2018 6:48:32 PM MYT
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….
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.