Changing the date format for a date range programmatically - java

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.

Related

How to Compare UTC format converted date in java [duplicate]

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

1 hour time difference daylight saving time issue

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;
}

Convert input String date time from different timezone to UTC

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.
}

convert string to date in java in format 2012-07-27

i have the input string as 2012-07-27 and i want the output as date but with the same format like 2012-07-27
my code is
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Date today = df.parse("20-12-2005");
System.out.println("Today = " + df.format(today));
} catch (ParseException e) {
e.printStackTrace();
}
my output is
Fri Jul 27 00:00:00 IST 2012
but i want to return the date object like like 2012-07-26 23:59:59 instead of a string any help please
any help is very thank full
You can use your same SimpleDateFormat you used to parse the date, to format the date into a string.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = formatter.parse("2012-07-27");
System.out.println(date1); // prints Fri Jul 27 00:00:00 IST 2012
System.out.println(formatter.format(date1)); // prints 2012-07-26
First, I think it's important to note that System.out.println implicitly invokes the toString method of its argument. The argument must be an Object or a subclass of it. And Date is a subclass of Object. That being said, take a look at the 1.7 Date#toString implementation,
public String toString() {
// "EEE MMM dd HH:mm:ss zzz yyyy";
BaseCalendar.Date date = normalize();
StringBuilder sb = new StringBuilder(28);
int index = date.getDayOfWeek();
if (index == gcal.SUNDAY) {
index = 8;
}
convertToAbbr(sb, wtb[index]).append(' '); // EEE
convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' '); // MMM
CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd
CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':'); // HH
CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
TimeZone zi = date.getZone();
if (zi != null) {
sb.append(zi.getDisplayName(date.isDaylightTime(), zi.SHORT, Locale.US)); // zzz
} else {
sb.append("GMT");
}
sb.append(' ').append(date.getYear()); // yyyy
return sb.toString();
}
The string representation of a Date object is specified as EEE MMM dd HH:mm:ss zzz yyyy. This is exactly what you're seeing.
If you want to display a Date object in a different format, use the SimpleDateFormat class. Its sole purpose is to add flexibility to the way a Date object is represented as a string.
Also...
One possible, albeit ridiculous workaround would be to create your own wrapper class,
public class MyDate{
private final Date d;
private final SimpleDateFormat sdf;
public(Date d, SimpleDateFormat sdf){
this.d = d;
this.sdf = sdf;
}
// not recommended...should only be used for debugging purposes
#Override
public String toString(){
return sdf.format(d);
}
}
You must use another SimpleDateFormat with the desired output format (format())
You can get a String representation for a date using the same SimpleDateFormat. The format method does this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse("2012-07-27");
System.out.println(sdf.format(date1);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse("2012-07-27");
System.out.println(dateFormat.format(date));
There is no "format" property in java.util.Date. A Date instance is rather a simple object representing a moment in time (effectively, it's state is only defined by a unix timestamp it stores internally).
As others noted, use (for example) a SimpleDateFormat to print a Date instance as into a string.
tl;dr
LocalDate.parse( "2012-07-27" )
.toString()
2012-07-27
Details
The modern way is with the java.time classes.
The LocalDate class represents a date-only value without time-of-day and without time zone.
Standard format
Your input string format happens to comply with the ISO 8601 standard. The java.time classes use ISO 8601 formats by default when parsing/generating strings that represent date-time values. So no need to specify a formatting pattern at all.
LocalDate ld = LocalDate.parse( "2012-07-27" );
Do not conflate date-time objects with Strings representing their value. A date-time class/object can parse a string and generate a string, but the String is always a separate and distinct object.
String output = ld.toString();
2012-07-27
Custom format
If your input is non-standard, define a DateTimeFormatter to match.
String input = "20-12-2005" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
LocalDate ld = LocalDate.parse( input , f ) ;
ld.toString(): 2012-07-27
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 and 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 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.

How can I convert Json Date to Java Date

I am trying to convert Json date string to java date format. However, it gives error when it comes to "return df.parse( tarih )" line.
JSON :
{"DateFrom":"\/Date(1323087840000+0200)\/"}
Java code :
private Date JSONTarihConvert(String tarih) throws ParseException
{
SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssz" );
if ( tarih.endsWith( "Z" ) ) {
tarih = tarih.substring( 0, tarih.length() - 1) + "GMT-00:00";
} else {
int inset = 6;
String s0 = tarih.substring( 6, tarih.length()-1 - inset );
String s1 = tarih.substring( tarih.length()- inset,tarih.length()-2 );
tarih = s0 + "GMT" + s1;
}
return df.parse( tarih );
}
When I call this method, tarih parameter is: /Date(1323087840000+0200)/
As you're interested in a Date object and the JSON occurs to me to be a unix timestamp.
Therefore I'd recommend you the Date(long milliseconds) constructor :)
private Date JSONTarihConvert(String tarih) throws ParseException{
long timestamp = getTimeStampFromTarih(tarih);
return new Date(timestamp);
}
Where getTimeStampFromTarih extracts the milliseconds before the occurrence of "+"
This will work surely
String date = "/Date(1376841597000)/";
Calendar calendar = Calendar.getInstance();
String datereip = date.replace("/Date(", "").replace(")/", "");
Long timeInMillis = Long.valueOf(datereip);
calendar.setTimeInMillis(timeInMillis);
System.out.println(calendar.getTime().toString("dd-MMM-yyyy h:mm tt"));//It Will Be in format 29-OCT-2014 2:26 PM
First replace string like this :
String str= ConvertMilliSecondsToFormattedDate(strDate.replace("/Date(","").replace(")/", ""));
Then Convert it like this:
public static String ConvertMilliSecondsToFormattedDate(String milliSeconds){
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(Long.parseLong(milliSeconds));
return simpleDateFormat.format(calendar.getTime());
}
You will Need to type cast date:
String rawdate = "/Date(1995769286000)/";
Calendar calendarins = Calendar.getInstance();
String datereip = rawdate.replace("/Date(", "").replace(")/", "");
Long timeInMillis = Long.valueOf(datereip);
calendar.setTimeInMillis(timeInMillis);
System.out.println(calendar.getTime().toString("dd-MMM-yyyy h:mm tt"));
Unless you have a reason not to, you should be using a parser to serialize and de-serialize objects. Like Jackson parser.
java.time
This is the modern answer (since 2014).
First I want to make sure the timestamp I have really lives up to the format I expect. I want to make sure if one day it doesn’t, I don’t just pretend and the user will get incorrect results without knowing they are incorrect. So for parsing the timestamp string, since I didn’t find a date-time format that would accept milliseconds since the epoch, I used a regular expression:
String time = "/Date(1479974400000-0800)/";
Pattern pat = Pattern.compile("/Date\\((\\d+)([+-]\\d{4})\\)/");
Matcher m = pat.matcher(time);
if (m.matches()) {
Instant i = Instant.ofEpochMilli(Long.parseLong(m.group(1)));
System.out.println(i);
}
This prints:
2016-11-24T08:00:00Z
It is not clear to me whether you need to use the zone offset and for what purpose. But since we’ve got it, why not retrieve it from the matcher and use it for forming an OffsetDateTime, a date and time with UTC offset. Here’s how:
ZoneOffset zo = ZoneOffset.of(m.group(2));
OffsetDateTime odt = OffsetDateTime.ofInstant(i, zo);
System.out.println(odt);
2011-12-05T14:24+02:00
If you need an old-fashioned java.util.Date for some legacy API:
System.out.println(Date.from(i));
Or if using the backport mentioned in the links below:
System.out.println(DateTimeUtils.toDate(i));
On my computer it prints
Mon Dec 05 13:24:00 CET 2011
The exact output will depend on your time zone.
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.

Categories