Conversion of string to date - java

I have a date in this format (Thu Feb 11 00:00:00 GMT 530 2016) which is a string and I want to convert this to a simple date format (dd/mm/yyyy).
I have used the below code but it does not work:
SimpleDateFormat fmt123 = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
try {
refDt = fmt123.parse(refDate);
logger.log(Level.SEVERE, "date after parsing "+refDt);
}
catch (ParseException e1) {
e1.printStackTrace();
}
It gives me the result of: Tue Feb 12 00:00:00 UTC 530
How can I convert this?

What you want to achieve is a two-step process.
Step 1 - Parsing existing string
You are very close, but as you've noticed the 530 part (I guess it is milliseconds) is parsed as year.
Use following code to create the instance of SimpleDateFormat used for parsing
new SimpleDateFormat("EEE MMM dd HH:mm:ss z SSS yyyy")
Step 2 - Formatting
Once you've parsed your date object, you'd need to present it to the user. Typically you would use new SimpleDateFormat("dd/MM/yyyy") and use it to output the date. This will use your local machine settings (such as timezone) to do the formatting. Usually it is sufficient.
But this is far more complex...
Timezones - the same time will mean a different date in different timezones. What is 2 AM, 11 Feb 2016 in Europe/Amsterdam is 8 PM, 10 Feb 2016 in America/Boston (or correct me if I am wrong).
Different calendar - you've probably already heart about Gregorian, Julian or Chinese calendar. The same time moment might have different days/month or year if expressed in different calendars. Fortunately majority of time we're talking about Gregorian calendar...
There is a very nice article Date and time in Java that describes the complexities in more details.

Poor Format
That String Thu Feb 11 00:00:00 GMT 530 2016 apparently has a bad format. I assume the 530 is an offset-from-UTC. But it lacks a + or -, a serious omission. Also, while not required, a padding zero on a single-digit hour of an offset is advised (05 rather than 5).
FYI, +05:30 is the time zone for two time zones, Asia/Kolkata and for Asia/Colombo. See this list. No time zone has an offset of -05:30.
I suspect this string may not actually be parseable as-is. You will need to manipulate the input string before attempting a parse. Something like the following, but your code will have to be more flexible if your input strings may vary.
String input = "Thu Feb 11 00:00:00 GMT 530 2016".replace ( "GMT 530" , "GMT+05:30" );
java.time
The Question and other Answers use the old outmoded date-time classes. Classes such as java.util.Date/.Calendar & java.text.SimpleDateFormat have been supplanted by the java.time framework built into Java 8 and later.
The formatter codes in java.time are a bit different than those of SimpleTextFormat. Be sure to read the doc.
String input = "Thu Feb 11 00:00:00 GMT 530 2016".replace ( "GMT 530" , "GMT+05:30" );
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "EEE MMM dd HH:mm:ss z uuuu" );
ZonedDateTime zdtGmt = ZonedDateTime.parse ( input , formatter );
ISO 8601
The java.time classes use ISO 8601 formats by default in their toString method implementations.
String output = zdtGmt.toString ();
Time Zone
Let’s adjust into the specific time zone of Asia/Kolkata rather than GMT. A time zone is an offset-from-UTC plus a set of past, present, and future adjustment rules for anomalies such as Daylight Saving Time.
ZonedDateTime zdtAsiaKolkata = zdtGmt.withZoneSameInstant ( ZoneId.of ( "Asia/Kolkata" ) );
Dump to console.
System.out.println ( "input: " + input + " | zdtGmt: " + zdtGmt + " | output: " + output + " | zdtAsiaKolkata: " + zdtAsiaKolkata );
input: Thu Feb 11 00:00:00 GMT+05:30 2016 | zdtGmt: 2016-02-11T00:00+05:30[GMT+05:30] | output: 2016-02-11T00:00+05:30[GMT+05:30] | zdtAsiaKolkata: 2016-02-11T00:00+05:30[Asia/Kolkata]

Your format here
SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
should match your input
"Thu Feb 11 00:00:00 GMT 530 2016"
As is mentioned in the comments this causes the parses to think 530 is the year and it ignores the rest.
See SimpleDateFormat for details.

SimpleDateFormat fmt123 = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
try {
refDt = fmt123.parse(refDate);
logger.log(Level.SEVERE, "date after parsing "+refDt);
}
catch (ParseException e1) {
e1.printStackTrace();
}

Related

SimpleDateFormat parsed from String is one day ahead [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 days ago.
Improve this question
I have the below Calendar object for NewYork timezone.
TimeZone timeZone = TimeZone.getTimeZone("America/New_York");
Calendar calNewYork = Calendar.getInstance();
calNewYork.setTimeZone(timeZone);
Currently it is 13th Feb. I'm using the below code to construct the Date object for 13th Feb 4 pm.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
dateFormat.setTimeZone(timeZone);
Date closingTime = dateFormat.parse("2023/02/13 16:00:00");
When I print closingTime it is "Tue Feb 14 02:30:00 IST 2023" in India Tz which translates to 14th Feb 4 pm NewYork time. Why did it bump the date by an extra day?
The reason the date got bumped by an extra day is because of the time zone difference between "America/New_York" and "IST" (Indian Standard Time). The time zone difference between the two is 10.5 hours. When you convert the time from one time zone to another, it may result in a change in the date. In your case, the time in New York is 4 PM on the 13th of February, but in India, it's already the next day (14th of February) due to the time zone difference, which is why the date got bumped by an extra day.
You can resolve this issue by using a time zone aware date format like the Java 8 date-time API (LocalDateTime, ZonedDateTime, etc.) instead of SimpleDateFormat, which is time zone unaware. That way, you can ensure that the date and time are always in the correct time zone, and you won't have to worry about date changes due to time zone differences.
(…) "Tue Feb 14 02:30:00 IST 2023" in India Tz (…) translates to 14th Feb 4 pm NewYork time.
It does not…
At that time "Asia/Kolkata" was 10:30h ahead of "America/New_York". You can see that if you carefully parse and format with SimpleDateFormats that have different TimeZones set and compare the output considering the getTime() method of the Date. It matters which zone is set in the SimpleDateFormat when you parse because your String does not provide a zone, the format assumes one.
See the following example…
public static void main(String[] args) throws ParseException {
// two time zones for parsing and formatting
TimeZone tzNY = TimeZone.getTimeZone("America/New_York");
TimeZone tzKol = TimeZone.getTimeZone("Asia/Kolkata");
// input format for New York
SimpleDateFormat nyFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// set the corresponding time zone
nyFormat.setTimeZone(tzNY);
// input format for
SimpleDateFormat kolFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// set the corresponding time zone
kolFormat.setTimeZone(tzKol);
/*
* parse the same values of date and time of day
* using the two different formats
* (this will lead to two different moments in time)
*/
Date ctNy = nyFormat.parse("2023/02/13 16:00:00");
Date ctKol = kolFormat.parse("2023/02/13 16:00:00");
// output format for New York
SimpleDateFormat outFormatNY = new SimpleDateFormat(
"EEE MMM dd HH:mm:ss z yyyy",
Locale.ENGLISH
);
// set the corresponding time zone
outFormatNY.setTimeZone(tzNY);
// output format for Kolkata
SimpleDateFormat outFormatKol = new SimpleDateFormat(
"EEE MMM dd HH:mm:ss z yyyy",
Locale.ENGLISH
);
// set the corresponding time zone
outFormatKol.setTimeZone(tzKol);
// print the results formatted in the different zones and their epoch millis
System.out.println(String.format("%28s | %13s | %-30s",
"America/New_York",
"Epoch Millis",
"Asia/Kolkata"));
System.out.println("—".repeat(75));
System.out.println(String.format("%28s | %13d | %-30s",
outFormatNY.format(ctNy),
ctNy.getTime(),
outFormatKol.format(ctNy)));
System.out.println(String.format("%28s | %13d | %-30s",
outFormatNY.format(ctKol),
ctKol.getTime(),
outFormatKol.format(ctKol)));
}
Output:
America/New_York | Epoch Millis | Asia/Kolkata
———————————————————————————————————————————————————————————————————————————
Mon Feb 13 16:00:00 EST 2023 | 1676322000000 | Tue Feb 14 02:30:00 IST 2023
Mon Feb 13 05:30:00 EST 2023 | 1676284200000 | Mon Feb 13 16:00:00 IST 2023
You can have that in a much more intuitive way if you switch to java.time…

Convert string to date (CEST works fine, GMT+02:00 doesn't work)

Question
Why is my Android app unable to parse String str1= "Tue Jun 20 15:56:29 CEST 2017"?
I found some similar questions, but none of them helped me.
Sidenotes
In my project I have some Java applications which are running on a computer and some Android applications. They are able to communicate to each other.
In the messages are timestamps. However my Java applications are sending timestamps in a format like String str1= "Tue Jun 20 15:56:29 CEST 2017" and my Android apps like String str2 = "Tue Jun 20 13:40:37 GMT+02:00 2017". To save the message including the time I have to parse the incoming time to a date.
My Android-App
In my Android app I can't parse the String str1= "Tue Jun 20 15:56:29 CEST 2017" correctly:
java.text.ParseException: Unparseable date: "Tue Jun 20 15:56:29 CEST 2017"
String str2 = "Tue Jun 20 13:40:37 GMT+02:00 2017"is working fine.
Code:
String str1 = "Tue Jun 20 14:53:08 CEST 2017";
SimpleDateFormat formatter = new SimpleDateFormat("EE MMM dd HH:mm:ss zzzz yyyy", Locale.US);
try {
Date date = formatter.parse(str1);
} catch (ParseException e) {
e.printStackTrace();
}
// test
String str2 = "Tue Jun 20 13:40:37 GMT+02:00 2017";
formatter = new SimpleDateFormat("EE MMM dd HH:mm:ss zzzz yyyy", Locale.US);
try {
Date date = formatter.parse(str2);
} catch (ParseException e) {
e.printStackTrace();
}
My Java-App
However, my Java application can parse both strings correctly.
Code:
String str = "Tue Jun 20 14:53:08 CEST 2017";
SimpleDateFormat formatter = new SimpleDateFormat("EE MMM dd HH:mm:ss zzzz yyyy", Locale.US);
try {
Date date = formatter.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
// test
str = "Tue Jun 20 13:40:37 GMT+02:00 2017";
formatter = new SimpleDateFormat("EE MMM dd HH:mm:ss zzzz yyyy", Locale.US);
try {
Date date = formatter.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
ThreeTen Solution
String to LocalDateTime
To convert my incoming string I'm using the following code:
String time = "Mon Jun 26 15:42:51 GMT 2017";
DateTimeFormatter gmtDateTimeFormatter = DateTimeFormatter.ofPattern("EE MMM dd HH:mm:ss 'GMT' yyyy", Locale.ENGLISH));
LocalDateTime timestamp = LocalDateTime.parse(time, gmtDateTimeFormatter);
LocalDateTime to String
To convert my LocalDateTime to a string I used this:
LocalDateTime timestamp = LocalDateTime.now();
DateTimeFormatter gmtDateTimeFormatter = DateTimeFormatter.ofPattern("EE MMM dd HH:mm:ss 'GMT' yyyy", Locale.ENGLISH));
String time = gmtDateTimeFormatter.format(timestamp);
Maybe there's a difference on how Android handles the zzzz pattern (probably Java's implementation handles it better than Android, so it "guesses" the correct timezone in a way that Android doesn't). I don't know.
Anyway, may I suggest you to avoid using those old classes? These old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.
To parse both formats, you can use a DateTimeFormatter with optional sections. That's because CEST is a timezone short name and GMT+02:00 is an UTC offset, so if you want to parse both with the same formatter, you'll need to use one optional section for each format.
Another detail is that short names like CET or CEST are ambiguous and not standard. The new API uses IANA timezones names (always in the format Continent/City, like America/Sao_Paulo or Europe/Berlin).
So, you need to choose one timezone that suits your needs. In the example below, I've just picked a timezone that's in CEST (Europe/Berlin), but you can change it according to what you need - you can get a list of all names using ZoneId.getAvailableZoneIds().
As the new API doesn't resolve CEST (because of its ambiguity), I need to create a set with the prefered timezone in order to correctly parse the input:
// when parsing, if finds ambiguous CET or CEST, it uses Berlin as prefered timezone
Set<ZoneId> set = new HashSet<>();
set.add(ZoneId.of("Europe/Berlin"));
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
// your pattern (weekday, month, day, hour/minute/second)
.appendPattern("EE MMM dd HH:mm:ss ")
// optional timezone short name (like "CST" or "CEST")
.optionalStart().appendZoneText(TextStyle.SHORT, set).optionalEnd()
// optional GMT offset (like "GMT+02:00")
.optionalStart().appendPattern("OOOO").optionalEnd()
// year
.appendPattern(" yyyy")
// create formatter (using English locale to make sure it parses weekday and month names correctly)
.toFormatter(Locale.US);
To parse Tue Jun 20 14:53:08 CEST 2017, just use the formatter:
ZonedDateTime z1 = ZonedDateTime.parse("Tue Jun 20 14:53:08 CEST 2017", fmt);
System.out.println(z1);
The output is:
2017-06-20T14:53:08+02:00[Europe/Berlin]
Note that CEST was mapped to Europe/Berlin, according to the set we created.
To parse Tue Jun 20 13:40:37 GMT+02:00 2017, we can use the same formatter. But GMT+02:00 can be in a lot of different regions, so the API can't map it to a single timezone. To convert it to the correct timezone, I need to use withZoneSameInstant() method:
// parse with UTC offset
ZonedDateTime z2 = ZonedDateTime.parse("Tue Jun 20 13:40:37 GMT+02:00 2017", fmt)
// convert to Berlin timezone
.withZoneSameInstant(ZoneId.of("Europe/Berlin"));
System.out.println(z2);
The output is:
2017-06-20T13:40:37+02:00[Europe/Berlin]
PS: the first case (z1) works in Java 8, but in ThreeTen Backport it's not setting the timezone to Berlin. To fix it, just call .withZoneSameInstant(ZoneId.of("Europe/Berlin")) as we did with z2.
If you still need to use java.util.Date, you can convert from and to the new API.
In java.time, new methods were added to Date class:
// convert ZonedDateTime to Date
Date date = Date.from(z1.toInstant());
// convert back to ZonedDateTime (using Berlin timezone)
ZonedDateTime z = date.toInstant().atZone(ZoneId.of("Europe/Berlin"));
In ThreeTen backport (and Android), you can use the org.threeten.bp.DateTimeUtils class:
// convert ZonedDateTime to Date
Date date = DateTimeUtils.toDate(z1.toInstant());
// convert back to ZonedDateTime (using Berlin timezone)
ZonedDateTime z = DateTimeUtils.toInstant(date).atZone(ZoneId.of("Europe/Berlin"));
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Do not use a fixed text for the timezone:
Do not use a fixed text (e.g. 'GMT') for the timezone as you have done because that approach may fail for other locales.
Solution using java.time, the modern Date-Time API:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(parse("Tue Jun 20 14:53:08 CEST 2017"));
System.out.println(parse("Tue Jun 20 13:40:37 GMT+02:00 2017"));
}
static ZonedDateTime parse(String strDateTime) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("E MMM d H:m:s z u", Locale.ENGLISH);
return ZonedDateTime.parse(strDateTime, dtf);
}
}
Output:
2017-06-20T14:53:08+02:00[Europe/Paris]
2017-06-20T13:40:37+02:00[GMT+02:00]
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Java simpledateformat Unparseable date, even though the format appears to be right

I've got a silly problem, here's my code:
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss zZ",Locale.US);
System.out.println(dateFormat.format(new Date()));
try {
wou.setDateStart(dateFormat.parse(date));
wou.setDateEnd(dateFormat.parse(date));
} catch (ParseException e) {
System.out.println(e.getCause() + " " + e.getMessage());
e.printStackTrace();
}
the result is following:
Fri Jun 05 2015 15:34:29 GMT+0000
null Unparseable date: "Fri Jun 05 2015 17:30:00 GMT+0000"
What's wrong with my format? It outputs the current date in the same format as the date I want to parse, but keeps telling me that the date is unparseable...
I'm struggling that for over an hour and I'm completely lost...
EDIT:
I have no control over the date I need to parse (if I did, I would change it in a source to a format that I could consume)
Following code:
String date = request.getParameter("absencyDate");
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss z",Locale.US);
try {
System.out.println(dateFormat.format(new Date()));
System.out.println(date);
System.out.println(dateFormat.parse(date));
} catch (ParseException e1) {
Produces same error:
Fri Jun 05 2015 16:09:15 GMT
Fri Jun 05 2015 12:30:00 GMT+0000
java.text.ParseException: Unparseable date: "Fri Jun 05 2015 12:30:00 GMT+0000"
The problem is your use of zZ in the date format. It expects a simple name-based zone (z), followed by an RFC-822 zone (Z).
It works well if the default zone (or the zone set in the format) is not GMT, because then it just parses up to that point (matches the z), and then it parses the +0000 as the Z.
But when the zone is GMT, it actually tries to parse the part that follows it (+0000) as part of the z, because "GMT+hh:mm" is a valid zone for z, and that fails.
The date format appears deceivingly correct. But combining two timezone formats is not. It should either be a named time zone (which includes "GMT+00:00"), or an RFC 822 offset (which doesn't include the "GMT" designation).
Edit following OP edit
So you get your date parameter from somewhere, and they are sending it to you with a non-standard zone designation. GMT+0000 matches neither general time zone (should be GMT or GMT+00:00), RFC 822 time zone (should be +0000 without GMT), nor ISO 8601 time zone (should be +00 or +0000 or +00:00).
If you know that they will always be using GMT in their dates, I think the best you can do is:
"EEE MMM dd yyyy HH:mm:ss 'GMT'Z"
Which will take the GMT part as a literal string rather than a time zone designator, then interpret the time zone from whatever follows it.
Or if the source that generates that parameter is under your control, fix its format to use a proper time zone matching one of the standards.
java.time
The legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) are outdated and error-prone. It is recommended to stop using them completely and switch to java.time, the modern date-time API*.
Demo using modern date-time API:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
public class Main {
public static void main(String args[]) {
String dateStr = "Fri Jun 05 2015 17:30:00 GMT+0000";
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("EEE MMM d u H:m:s")
.appendLiteral(' ')
.appendZoneId()
.appendPattern("X")
.toFormatter(Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(dateStr, dtf);
System.out.println(zdt);
}
}
Output:
2015-06-05T17:30Z[GMT]
For any reason, if you need an object of java.util.Date from this object of ZonedDateTime, you can so as follows:
Date date = Date.from(zdt.toInstant());
Learn more about the the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

How to convert this "Tue Nov 13 14:35:04 +0000 2012" String format to date in Java?

How to convert the date Tue Nov 13 14:35:04 +0000 2012 String format to date in Java?
I know of Date.parse(String) but I don't know which format I should use for the date. Do I have to modify the string so that it can be parsed into date, and if yes then how?
Use SimpleDateFormat, with a format string of
"E MMM dd HH:mm:ss Z yyyy"
You should explicitly use Locale.US assuming these will definitely use English month/day names. (You don't want to be trying to parse French names just because the default locale is French, for example.)
Also, don't forget that the Date value returned will have no knowledge of the original time zone - it will have the right value for the instant represented in the original text, but don't expect the result of calling toString() to use the same zone - Date.toString() always uses the default time zone.
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);
Date test = sdf.parse("Tue Nov 13 14:35:04 +0000 2012");
System.out.print(test.toString());

How to convert a date in this format (Tue Jul 13 00:00:00 CEST 2010) to a Java Date (The string comes from an alfresco property)

i'm managing a date that comes from an Alfresco Properties and is in the specified (Tue Jul 13 00:00:00 CEST 2010) and i need to convert it to a Java date...i've looked around and found millions of posts for various string to date conversion form and also this page and so i tried something like this:
private static final DateFormat alfrescoDateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
Date dataRispostaDate = alfrescoDateFormat.parse(dataRisposta);
But it throws an exception.(The exception is (SSollevata un'eccezione durante la gestione della data: java.text.ParseException: Unparseable date: "Tue Jul 13 00:00:00 CEST 2011").
I post the complete code:
try {
QName currDocTypeQName = (QName) nodeService.getType(doc);
log.error("QName:["+currDocTypeQName.toString()+"]");
if (currDocTypeQName != null) {
String codAtto = AlfrescoConstants.getCodAttoFromQName(currDocTypeQName.toString());
log.error("codAtto:["+codAtto+"]");
if (codAtto.equals(AlfrescoConstants.COD_IQT)){
List<ChildAssociationRef> risposteAssociate = nodeService.getChildAssocs(doc, AlfrescoConstants.QN_RISPOSTEASSOCIATE, RegexQNamePattern.MATCH_ALL);
for (ChildAssociationRef childAssocRef : risposteAssociate) {
// Vado a prendere il nodo
NodeRef risposta = childAssocRef.getChildRef();
String dataRisposta = (nodeService.getProperty(risposta, AlfrescoConstants.QN_DATA_RISPOSTA)).toString();
log.error("dataRisposta:["+dataRisposta+"]");
if (!dataRisposta.isEmpty()){
try {
Date dataDa = dmyFormat.parse(req.getParameter("dataDa"));
log.error("dataDa:["+dataDa.toString()+"]");
Date dataA = dmyFormat.parse(req.getParameter("dataA"));
log.error("dataA:["+dataA.toString()+"]");
Date dataRispostaDate = alfrescoDateFormat.parse(dataRisposta);
log.error("dataRispostaDate:["+dataRispostaDate.toString()+"]");
if (dataRispostaDate.after(dataDa) && dataRispostaDate.before(dataA)){
results.add(doc);
log.error("La data risposta è compresa tra le date specificate");
}else{
log.error("La data risposta non è compresa tra le date specificate");
}
} catch (ParseException e) {
log.error("Sollevata un'eccezione durante la gestione della data: " + e);
throw new RuntimeException("Formato data non valido");
}
}else{
log.error("La data risposta non è specificata");
}
}
}else{
results.add(doc);
}
}
} catch (Exception e) {
log.error("Sollevata un'eccezione durante la gestione del codice atto nel webscript nicola: " + e);
}
Anyone can help?
Basically your problem is that you are using a SimpleDateFormat(String pattern) constructor, where javadoc says:
Constructs a SimpleDateFormat using
the given pattern and the default date
format symbols for the default locale.
And if you try using this code:
DateFormat osLocalizedDateFormat = new SimpleDateFormat("MMMM EEEE");
System.out.println(osLocalizedDateFormat.format(new Date()))
you will notice that it prints you month and day of the week titles based on your locale.
Solution to your problem is to override default Date locale using SimpleDateFormat(String pattern, Locale locale) constructor:
DateFormat dateFormat = new SimpleDateFormat(
"EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
dateFormat.parse("Tue Jul 13 00:00:00 CEST 2011");
System.out.println(dateFormat.format(new Date()));
tl;dr
ZonedDateTime.parse( // Produce a `java.time.ZonedDateTime` object.
"Wed Jul 13 00:00:00 CEST 2011" , // Corrected `Tue` to `Wed`.
DateTimeFormatter.ofPattern( "EEE MMM d HH:mm:ss zzz uuuu" , Locale.US )
)
2011-07-13T00:00+02:00[Europe/Paris]
Bad data: Wed vs Tue
You input string Tue Jul 13 00:00:00 CEST 2011 is invalid. July 13 of 2011 was a Wednesday, not a Tuesday.
String input = "Wed Jul 13 00:00:00 CEST 2011" ; // Corrected `Tue` to `Wed`.
java.time
The modern approach uses the java.time classes rather than the troublesome old legacy date-time classes seen in other Answers.
Define a formatting pattern to match your input string. Notice the Locale, which defines the human language to be used in parsing name of month and name of day-of-week.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM d HH:mm:ss zzz uuuu" , Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
zdt.toString(): 2011-07-13T00:00+02:00[Europe/Paris]
Time zone
Your CEST is a pseudo-zone, not a true time zone. Never use these. They are not standardized, and are not even unique(!).
The ZonedDateTime class will make a valiant effort at guessing the intention behind such a 3-4 character pseudo-zone. Your CEST happened to work here, interpreted as Europe/Paris time zone. But you cannot rely on the guess being 100% successful. Instead, avoid such pseudo-zones entirely.
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( "Europe/Paris" ); // https://time.is/Paris
LocalDate today = LocalDate.now( z ); // Current date varies around the globe by zone.
ISO 8601
Your input string’s format is terrible. When serializing date-time values as text, use only the standard ISO 8601 formats.
The ZonedDateTime class wisely extends the standard format by appending the name of the time zone in square brackets as seen in examples above.
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 (JSR 310) 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.
Based on your comments, I believe that your property is actually of type d:date or d:datetime. If so, the property will already be coming back from Alfresco as a java Date object. So, all you'd need to do is:
NodeRef risposta = childAssocRef.getChildRef();
Date dataRisposta = (Date)nodeService.getProperty(risposta, AlfrescoConstants.QN_DATA_RISPOSTA);
The problem is that CEST is not a timezone Java supports. You can use "CST".
The Javadoc for TimeZone notes:
Three-letter time zone IDs
For compatibility with JDK 1.1.x, some other three-letter time zone IDs (such as "PST", "CTT", "AST") are also supported. However, their use is deprecated because the same abbreviation is often used for multiple time zones (for example, "CST" could be U.S. "Central Standard Time" and "China Standard Time"), and the Java platform can then only recognize one of them.
For three/four letter timezone support I suggest you try JodaTime which may do a better job.
String dataRisposta = "Tue Jul 13 00:00:00 CST 2010";
Date dataRispostaDate = alfrescoDateFormat.parse(dataRisposta);
System.out.println(dataRispostaDate);
prints
Tue Jul 13 07:00:00 BST 2010
String[] ids = TimeZone.getAvailableIDs();
Arrays.sort(ids);
for (String id : ids) {
System.out.println(id);
}
prints
...
CAT
CET
CNT
CST
CST6CDT
CTT
...
Try this function I had the same issue.
public String getMyDate(String myDate, String requiredFormat, String mycurrentFormat) {
DateFormat dateFormat = new SimpleDateFormat(returnFormat);
Date date = null;
String returnValue = "";
try {
date = new SimpleDateFormat(myFormat, Locale.ENGLISH).parse(myDate);
returnValue = dateFormat.format(date);
} catch (ParseException e) {
returnValue = myDate;
}
return returnValue;
}
Example:
Wed May 06 13:01:29 EDT 2020 i.e "EEE MMM dd HH:mm:ss zzz yyyy" is mycurrentFormat
4.May.2020 i.e. "d.MMM.yyyy" is my requiredFormat
Date date = new Date();
getMyDate(date.toString(), "d.MMM.yyyy", "EEE MMM dd HH:mm:ss zzz yyyy")

Categories