I have two Date objects with the below format.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String matchDateTime = sdf.parse("2014-01-16T10:25:00");
Date matchDateTime = null;
try {
matchDateTime = sdf.parse(newMatchDateTimeString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// get the current date
Date currenthDateTime = null;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date dt = new Date();
String currentDateTimeString = dateFormat.format(dt);
Log.v("CCCCCurrent DDDate String is:", "" + currentDateTimeString);
try {
currenthDateTime = sdf.parse(currentDateTimeString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now I want to compare the above two dates along with time.
How should I compare in Java.
Thanks
Since Date implements Comparable<Date>, it is as easy as:
date1.compareTo(date2);
As the Comparable contract stipulates, it will return a negative integer/zero/positive integer if date1 is considered less than/the same as/greater than date2 respectively (ie, before/same/after in this case).
Note that Date has also .after() and .before() methods which will return booleans instead.
An Alternative is....
Convert both dates into milliseconds as below
Date d = new Date();
long l = d.getTime();
Now compare both long values
Use compareTo()
Return Values
0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.
Like
if(date1.compareTo(date2)>0)
An alternative is Joda-Time.
Use DateTime
DateTime date = new DateTime(new Date());
date.isBeforeNow();
or
date.isAfterNow();
// Get calendar set to the current date and time
Calendar cal = Calendar.getInstance();
// Set time of calendar to 18:00
cal.set(Calendar.HOUR_OF_DAY, 18);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// Check if current time is after 18:00 today
boolean afterSix = Calendar.getInstance().after(cal);
if (afterSix) {
System.out.println("Go home, it's after 6 PM!");
}
else {
System.out.println("Hello!");
}
The other answers are generally correct and all outdated. Do use java.time, the modern Java date and time API, for your date and time work. With java.time your job has also become a lot easier compared to the situation when this question was asked in February 2014.
String dateTimeString = "2014-01-16T10:25:00";
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString);
LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());
if (dateTime.isBefore(now)) {
System.out.println(dateTimeString + " is in the past");
} else if (dateTime.isAfter(now)) {
System.out.println(dateTimeString + " is in the future");
} else {
System.out.println(dateTimeString + " is now");
}
When running in 2020 output from this snippet is:
2014-01-16T10:25:00 is in the past
Since your string doesn’t inform of us any time zone or UTC offset, we need to know what was understood. The code above uses the device’ time zone setting. For a known time zone use like for example ZoneId.of("Asia/Ulaanbaatar"). For UTC specify ZoneOffset.UTC.
I am exploiting the fact that your string is in ISO 8601 format. The classes of java.time parse the most common ISO 8601 variants without us having to give any formatter.
Question: For Android development doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Wikipedia article: ISO 8601
Related
I have an application where I want to change the date format in 'From' and 'To'.
Lets assume, I have a date range like 2018-06-11 - 2018-06-14. Now, I want to change it in some other format as 11 June, 2018 - 14 June, 2018.
Please refer the code below, I have tried:
String strDate = "2018-06-11 - 2018-06-14";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = format.parse(strDate);
format = new SimpleDateFormat("dd MMMM, yyyy");
String strFinalDate = format.format(date);
tv4.setText(strFinalDate);
} catch (ParseException e) {
e.printStackTrace();
}
Also, I tried the below code as well:
String strDate = "2018-06-11 - 2018-06-14";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd - yyyy-MM-dd");
try {
Date date = format.parse(strDate);
format = new SimpleDateFormat("dd MMMM, yyyy - dd MMMM, yyyy");
String strFinalDate = format.format(date);
tv4.setText(strFinalDate);
} catch (ParseException e) {
e.printStackTrace();
}
First, set of code runs smoothly, but converts only the 'From' and doesn't even checks for 'To' date.
And, second set of code returns an error which says, java.text.ParseException: Unparseable date: "2017-01-11 - 2017-01-14
Have I skipped anything in this code?
Please notify me if I have.
Thanks!
I suggest
DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
String strDate = "2018-06-11 - 2018-06-14";
String[] strDates = strDate.split(" - ");
if (strDates.length != 2) {
throw new IllegalStateException("Wrong range format " + strDate
+ ", must be yyyy-MM-dd - yyyy-MM-dd");
}
String strFinalDate = LocalDate.parse(strDates[0]).format(dateFormatter)
+ " - " + LocalDate.parse(strDates[1]).format(dateFormatter);
System.out.println(strFinalDate);
Output on my Java with US English locale:
11 June 2018 - 14 June 2018
You don’t get the comma after “June” because this is not considered standard, so consider if this isn’t really an advantage. The output will depend on locale setting, which may be an advantage too. Or specify explicit locale for example:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG)
.withLocale(Locale.UK);
I am using and recommending java.time, the modern Java date and time API.
What went wrong in your code?
No matter if you use an old-fashiuoned Date or a modern LocalDate, such an object can only hold one date, not a date range. In your first attempt SimpleDateFormat parsed the first date (since it matched your pattern) and then ignored the remainder of the string. So when you formatted the parsed date, you got
11 June, 2018
In your seconds attempt both dates were parsed, but into the same Date object, so only the values of the second date were kept. When printing the date its values were also printed twice since the format pattern for formatting contains the format twice:
14 June, 2018 - 14 June, 2018
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.timeto Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
As I stated in my comment above, you have to split your strDate String into two different String variables. Have a look at the code below
String strDate = "2018-06-11 - 2018-06-14";
String[] fromToDatesStr = strDate.split(" - ");
String fromDateStr = fromToDatesStr[0];
String toDateStr = fromToDatesStr[1];
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date fromDate = null;
Date toDate = null;
try {
fromDate = format.parse(fromDateStr);
toDate = format.parse(toDateStr);
format = new SimpleDateFormat("dd MMMM, yyyy");
String strFromFinalDate = format.format(fromDate);
String strToFinalDate = format.format(toDate);
} catch (ParseException e) {
e.printStackTrace();
}
String strFromFinalDate and String strToFinalDate now contain the dates formatted as you desire.
Function to convert server date to device local time:
public static String convertIntoLocalTime(String strTime, String whichTimeZone, String dateFormat) {
String strLocalTime = null;
try {
SimpleDateFormat sdf = getSimpleDateFormat(dateFormat, whichTimeZone);
Date date = sdf.parse(strTime);
AppLog.e(TAG,"Timezone = " + whichTimeZone);
AppLog.e(TAG,"Date = " + strTime);
AppLog.e(TAG,"Date in CET = " + date.toString());
AppLog.e(TAG,"inDaylightTime = " + sdf.getTimeZone().inDaylightTime(date));
AppLog.e(TAG,"DST savings = " + sdf.getTimeZone().getDSTSavings());
if (sdf.getTimeZone().getDSTSavings() == 3600000) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, 1);
Date oneHourBack = cal.getTime();
SimpleDateFormat local = getLocalSimpleDateFormat(dateFormat);
strLocalTime = local.format(oneHourBack);
} else {
SimpleDateFormat local = getLocalSimpleDateFormat(dateFormat);
strLocalTime = local.format(date);
}
} catch (ParseException e) {
AppLog.e(TAG, e.getMessage(), e);
}
AppLog.e(TAG,"Local Time = " + strLocalTime);
return strLocalTime;
}
Function to get simple date format:
private static SimpleDateFormat getSimpleDateFormat(String format, String tz) {
TimeZone timeZone = TimeZone.getTimeZone(tz);
timeZone.useDaylightTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format, Locale.getDefault());
simpleDateFormat.setTimeZone(timeZone);
return simpleDateFormat;
}
Function to get simple date format for local device conversion:
/**
* #param format
* #return
*/
private static SimpleDateFormat getLocalSimpleDateFormat(String format) {
TimeZone timeZone = TimeZone.getDefault();
timeZone.useDaylightTime();
SimpleDateFormat localSdf = new SimpleDateFormat(format, Locale.getDefault());
localSdf.setTimeZone(timeZone);
return localSdf;
}
Output:
Date = 2018-04-22 14:30
Date in CET = Sun Apr 22 13:30:00 GMT+01:00 2018
inDaylightTime = true
DST savings = 3600000
Local Time = 2018-04-22 14:30
The above code was working perfectly fine earlier, for example we have 1 event on 1st of April where it was showing time correctly but at the moment starting from 21 April its showing additional 1 hour time.
I have tried to convert the date coming from server using UTC as well as CET but in both the cases its showing me additional one hour when converting it to device local time.
The above example is based on London timezone, whereas when we tried it in IST timezone it was returning the correct time.
We have handled DST time different by checking inDaylightTime function of timezone but it's not working.
I am sure that there is something related to DST but I am not able to figure it out. Thanks for your help?
First, you are using the old and long outdated date and time classes: SimpleDateFormat, Date, Calendar and TimeZone. These are renowned for being poorly designed and sometimes troublesome to work with. My first suggestion is you rewrite your code using java.time, the modern Java date and time API. It is much less buggy, and I expect that you will more easily develop correct code.
That said, no matter if you use the old-fashioned or the modern classes, don’t handle summer time yourself. The library classes will do it for you. Your job is to get the time zones correct. Don’t add or subtract an hour to compensate for summer time. Look at other questions about converting from one time zone to another, there are many.
Don’t use three and four letter time zone abbreviations. CET is not a time zone. IST is ambiguous, it may mean Irish Summer Time, Israel Standard Time or India Standard Time. The countries in Europe that use CET in winter have used CEST (Central European Summer Time) since March 26, 2018.
Instead give server time zone as continent/city such as Europe/London if this is the server time zone. It’s unambiguous.
Also make sure to set your device time zone to a true time zone. It seems you’ve got it set to GMT+01:00, which is a GMT offset, not a time zone. It agrees with Europe/London time zone and with CET in winter, but not after March 26.
Finally, you are adding 1 hour to your Calendar, turning it 1 hour forward, and then calling the Date you get from it oneHourBack. This looks wrong. Did you mean to subtract 1 hour, or did you mean that the variable should be oneHourForward?
EDIT: I probably haven’t understood exactly which time zones are the correct ones for you, and therefore not what would be the correct output for your code. So take the following only as a guess at what you were trying to accomplish. And please fill in the correct time zones.
public static String convertIntoLocalTime(
String strTime, String serverTimeZone, String dateFormat) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
ZonedDateTime serverDateTime = LocalDateTime.parse(strTime, formatter)
.atZone(ZoneId.of(serverTimeZone));
AppLog.e(TAG, "Server timezone = " + serverTimeZone);
AppLog.e(TAG, "Date = " + strTime);
AppLog.e(TAG, "Date in server timezone = " + serverDateTime.toString());
ZonedDateTime deviceTime = serverDateTime
.withZoneSameInstant(ZoneId.systemDefault());
String strLocalTime = deviceTime.format(formatter);
AppLog.e(TAG, "Device Time = " + deviceTime);
AppLog.e(TAG, "Local Time = " + strLocalTime);
return strLocalTime;
}
I tried setting my time zone to Europe/London and issuing the following call:
convertIntoLocalTime("2018-04-22 14:30", "Europe/Berlin", "yyyy-MM-dd HH:mm")
The output I got was:
Server timezone = Europe/Berlin
Date = 2018-04-22 14:30
Date in server timezone = 2018-04-22T14:30+02:00[Europe/Berlin]
Device Time = 2018-04-22T13:30+01:00[Europe/London]
Local Time = 2018-04-22 13:30
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
List of tz database time zones
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.timeto Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
I was not tested so try it first.
public String convertIntoLocalTime(String strTime, String whichTimeZone, String dateFormat) {
String strLocalTime = null;
strLocalTime=convertDateToUserTimeZone(strTime,whichTimeZone,dateFormat);
return strLocalTime;
}
public String convertDateToUserTimeZone(String strTime, String whichTimeZone, String dateFormat) {
String ourdate;
try {
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat, Locale.UK);
formatter.setTimeZone(TimeZone.getTimeZone(whichTimeZone));
Date value = formatter.parse(strTime);
TimeZone timeZone = TimeZone.getTimeZone("Asia/Kolkata");
SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormat, Locale.UK); //this format changeable
dateFormatter.setTimeZone(timeZone);
ourdate = dateFormatter.format(value);
//Log.d("OurDate", OurDate);
} catch (Exception e) {
ourdate = "00-00-0000 00:00";
}
return ourdate;
}
My system located in Singapore (timezone - "Asia/Singapore") receives a String datetime (yyyy-MM-dd HH:mm:ss) from a external system in Indonesia (timezone - "Asia/Jarkata").
How do I convert the received String datetime to UTC in java 1.7?
This is my code:
public void convertToUtc() {
String inputTime = "2018-02-02 10:09:00";
TimeZone inputTz = TimeZone.getTimeZone("Asia/Jarkarta");
TimeZone utcTz = TimeZone.getTimeZone("UTC");
SimpleDateFormat inputSdf = new SimpleDateFormat(DateTimeUtils.DATE_TIME_FORMAT);
inputSdf.setTimeZone(inputTz);
SimpleDateFormat utcSdf = new SimpleDateFormat(DateTimeUtils.ISO_DATE_TIME_FORMAT);
utcSdf.setTimeZone(utcTz);
// From time
Date fromDate = null;
try {
fromDate = inputSdf.parse(inputTime);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Convert to UTC
String sUtcDateTime = utcSdf.format(fromDate);
System.out.println("UTC: " + sUtcDateTime); // UTC: 2018-02-02T10:09:00.000Z. Expected 2018-02-02T03:09:00.000Z
}
janith1024’s answer is correct. However, I believe the real problem is that the old (and long outdated) TimeZone class behaves badly and doesn’t inform you of your spelling mistake. After all, we could all make that. So the real solution is to use java.time, the modern Java date and time API. On Java 7 (and 6) add ThreeTen Backport to your project, import:
import org.threeten.bp.ZoneId;
And then:
ZoneId inputTz = ZoneId.of("Asia/Jarkarta");
This gives you a org.threeten.bp.zone.ZoneRulesException: Unknown time-zone ID: Asia/Jarkarta. I should say that this greatly increases your chance of discovering your spelling error (the correct spelling is Asia/Jakarta).
The documentation of TimeZone.getTimeZone() says that it returns
the specified TimeZone, or the GMT zone if the given ID cannot be
understood.
However I am posting this answer because your issue is not just a lone example. Over and over we see questions on Stack Overflow coming from the old date and time classes showing surprising behaviour and in particular not detecting problems with the data we pass to them that it’s easy to detect. I very warmly recommend using the modern API instead.
In Java 8 and later, java.time is built-in, and you should import your date and time classes from java.time with subpackages rather than from org.threeten.bp.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.timeto Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
I check your code there was a spelling mistake in time zone so I correct it
public static void convertToUtc() {
String inputTime = "2018-02-02 10:09:00";
TimeZone inputTz = TimeZone.getTimeZone("Asia/Jakarta");
TimeZone utcTz = TimeZone.getTimeZone("UTC");
SimpleDateFormat inputSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
inputSdf.setTimeZone(inputTz);
SimpleDateFormat utcSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
utcSdf.setTimeZone(utcTz);
// From time
Date fromDate = null;
try {
fromDate = inputSdf.parse(inputTime);
}
catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Convert to UTC
String sUtcDateTime = utcSdf.format(fromDate);
System.out.println("UTC: " + sUtcDateTime); // print this UTC: 2018-02-02 03:09:00.
}
This question already has answers here:
Parse clock time in java 8
(2 answers)
Closed 6 years ago.
I would like to convert a variable string to a Time type variable, not Date using Java. the string look like this 17:40
I tried using the code below but this instance is a date type variable not time
String fajr_prayertime = prayerTimes.get(0);
DateFormat formatter = new SimpleDateFormat("HH:mm");
fajr_begins = (Date)formatter.parse(fajr_prayertime);
System.out.println(" fajr time " + fajr_begins);
However Netbean complains that I should insert an exception as below;
DateFormat formatter = new SimpleDateFormat("HH:mm");
try {
fajr_begins = (Date)formatter.parse(fajr_prayertime);
} catch (ParseException ex) {
Logger.getLogger(JavaFXApplication4.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(" fajr time " + fajr_begins);
Any idea how I can get the time out of the string above.
java.sql.Time timeValue = new java.sql.Time(formatter.parse(fajr_prayertime).getTime());
You might consider Joda Time or Java 8, which has a type called LocalTime specifically for a time of day without a date component.
Example code in Joda-Time 2.7/Java 8.
LocalTime t = LocalTime.parse( "17:40" ) ;
You might want to take a look at this example:
public static void main(String[] args) {
String myTime = "10:30:54";
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = null;
try {
date = sdf.parse(myTime);
} catch (ParseException e) {
e.printStackTrace();
}
String formattedTime = sdf.format(date);
System.out.println(formattedTime);
}
try {
SimpleDateFormat format = new SimpleDateFormat("hh:mm a"); //if 24 hour format
// or
SimpleDateFormat format = new SimpleDateFormat("HH:mm"); // 12 hour format
java.util.Date d1 =(java.util.Date)format.parse(your_Time);
java.sql.Time ppstime = new java.sql.Time(d1.getTime());
} catch(Exception e) {
Log.e("Exception is ", e.toString());
}
You can use the following code for changing the String value into the time equivalent:
String str = "08:03:10 pm";
DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
Date date = (Date)formatter.parse(str);
Hope this helps you.
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:MM");
simpleDateFormat.format(fajr_prayertime);
Joda-Time & java.time
Both Joda-Time and java.time (new in Java 8) offer a LocalTime class to represent a time-of-day without any date or time zone.
Example code, identical code for both java.time and Joda-Time.
LocalTime localTime = new LocalTime( "14:40" );
LocalTime deadline = new LocalTime( "15:30" );
boolean meetsDeadline = localTime.isBefore( deadline );
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. Hibernate 5 & JPA 2.2 support java.time.
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….
try...
java.sql.Time.valueOf("10:30:54");
String to Time (using an arbitrary time):
String myTime = "10:00:00";
Time startingTime = new Time (myTime);
String to Time (using currentTime):
String currentTime = getCurrentTime();
Time startingTime = new Time (currentTime);
Time to String:
private String getCurrentTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat("kkmmss");
String currentTime = dateFormat.format(System.currentTimeMillis());
return currentTime;
}
I am having a bit of trouble parsing a string date to a Date object. I use a DateFormat to parse the string, and when I print the value of the date, it gives me what I expect.
But when I try get the day, the month or the year it gives me the wrong values. For instance, the year is 2011, but when I do .getYear() it gives me 111. I have no idea why this is happening. Here is the relevant code segment:
Date dateFrom = null;
String gDFString = g.getDateFrom();
System.out.println(gDFString);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
try {
dateFrom = df.parse("04/12/2011");
System.out.println(dateFrom);
System.out.println(dateFrom.getYear());
} catch (ParseException e) {
e.printStackTrace();
}
When I out print dateFrom, I get Sun Dec 04 00:00:00 GMT 2011, which is what you would expect. But printing .getYear() returns 111.
I need to be able to get the day, month and year of the date for a time series graph.
Those methods have been deprecated. Instead, use the Calendar class.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public final class DateParseDemo {
public static void main(String[] args){
final DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
final Calendar c = Calendar.getInstance();
try {
c.setTime(df.parse("04/12/2011"));
System.out.println("Year = " + c.get(Calendar.YEAR));
System.out.println("Month = " + (c.get(Calendar.MONTH)));
System.out.println("Day = " + c.get(Calendar.DAY_OF_MONTH));
}
catch (ParseException e) {
e.printStackTrace();
}
}
}
Output:
Year = 2011
Month = 3
Day = 12
And as for the month field, this is 0-based. This means that January = 0 and December = 11. As stated by the javadoc,
Field number for get and set indicating the month. This is a
calendar-specific value. The first month of the year in the Gregorian
and Julian calendars is JANUARY which is 0; the last depends on the
number of months in a year.
Javadoc to the rescue:
Deprecated. As of JDK version 1.1, replaced by
Calendar.get(Calendar.YEAR) - 1900.
Returns a value that is the result of subtracting 1900 from the
year that contains or begins with the instant in time represented by
this Date object, as interpreted in the local time zone.
You should not use deprecated methods. Deprecated methods are methods which should not be used anymore. But whatever the method you're using, read its javadoc to know what it does.
President Evil nailed it, Date.getYear() returns a value that is the result of subtracting 1900 from the year that contains. And you you shouldn't use it.
But quick fix for the code in the question is:
Date dateFrom = null;
String gDFString = g.getDateFrom();
System.out.println(gDFString);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
try {
dateFrom = df.parse("04/12/2011");
System.out.println(dateFrom);
// Add 1900 to dateFrom.getYear()
System.out.println(dateFrom.getYear()+1900);
} catch (ParseException e) {
e.printStackTrace();
}
http://download.oracle.com/javase/1.4.2/docs/api/java/util/Date.html#getYear%28%29
The specification states that it returns the year minus 1900. Probably a good idea to avoid deprecated methods as well.
tl;dr
int year =
LocalDate.parse(
"04/12/2011" ,
DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( Locale.US )
).getYear() ;
2011
java.time
The troublesome java.util.Date class and its siblings are now supplanted by the excellent java.time classes.
String input = "04/12/2011";
Locale locale = Locale.US;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( locale );
LocalDate ld = LocalDate.parse( input , f );
The java.time classes utilize sane numbering, with:
Months 1-12 for January-December
2011 means 2011
Days of week are 1-7 for Monday-Sunday (per ISO 8601).
Interrogate the LocalDate for its constituent parts.
int year = ld.getYear(); // 2011
int month = ld.getMonthValue(); // 4
int dayOfMonth = ld.getDayOfMonth(); // 12
You can even ask for automatically localized name of month and name of day-of-week.
String monthName = ld.getMonth().getDisplayName( TextStyle.FULL_STANDALONE , Locale.CANDA_FRENCH ); // avril
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
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.
This is only a guess, but the 111 could be the number of years since 1900. Take a look at documentation/do some tests to verify this (I can't check at the moment)