I am trying to take date in string and its input format string and converting the date in output format. However after conversion into Date, the java code increases the number of hours by one. I am not able to understand what causes the bug.
My Code:
try {
DateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
DateFormat inputFormat = new SimpleDateFormat(format);
Date date = inputFormat.parse(parameterValue);
parameterValue = outputFormat.format(date);
return parameterValue;
} catch (ParseException ex) {
// take action
}
format string: ddMMMyyyy / hh:mm z
Input Date: 07DEC2015 / 10:02 GMT
Output Date: 07/12/2015 11:02:00
outputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
resolved it.
If you don't want to use timezone, in java 8 you can use LocalDate/LocalTime/LocalDateTime:
LocalDateTime localDateTimeInstance = LocalDateTime.parse(dateToBeConverted, DateTimeFormatter.ofPattern(formatOfDateToBeConverted));
return localDateTimeInstance.format("dd/MM/yyyy hh:mm:ss");
/*
Also check out ZoneDate, ZoneTime (for timezone)
Checkout - LocalDate, LocalTime
*/
Related
I got a timestamp as follows, 2019-10-17T07:10:39.021+10:30 but when I parse through the SimpleDateFormat then print again, it appear as 2019-10-17T07:40:39.021+11:00
Looks like it added the 30min to time then change the time zone. Is there is a way to fix that.
Date date = null;
String value = "2019-10-17T07:10:39.021+10:30";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.getDefault());
System.out.println("input :" + value);
try {
date = sdf.parse(value);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("output :" + sdf.format(date));
Result
input :2019-10-17T07:10:39.021+10:30
output :2019-10-17T07:40:39.021+11:00
Should be same as input.
The date string you have 2019-10-17T07:10:39.021+10:30consists of offset, so from java-8 you can use OffsetDateTime
A date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system, such as 2007-12-03T10:15:30+01:00.
OffsetDateTime dateTime = OffsetDateTime.parse(date);
System.out.println(dateTime.toString()); //2019-10-17T07:10:39.021+10:30
Why are you using Locale.getDefault(), that parameter is not necessary. Can you try just calling it as below,
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
I have a date that keeps giving me an error of
java.text.ParseException: Unparseable date: " 5 April 2017 "
All other dates (without word months) work fine
The code I am using is below:
VisitDate=VisitDate.trim();
if (VisitDate.matches(".*[a-z].*")){
SimpleDateFormat changeDate = new SimpleDateFormat("dd_MMM_yy", Locale.UK);
//Convert the string to a date
Date date = changeDate.parse(VisitDate);
//Reformat the date the way I like it
SimpleDateFormat dt1 = new SimpleDateFormat("dd_MM_yy");
//Convert back into a string
try {
VisitDate=dt1.format(date);
if(VisitDate==null){
SimpleDateFormat dt2 = new SimpleDateFormat("dd MM yy");
//Convert back into a string
VisitDate=dt2.format(date);
if(VisitDate==null){
SimpleDateFormat dt3 = new SimpleDateFormat("dd MMMM yy");
//Convert back into a string
VisitDate=dt3.format(date);
if(VisitDate==null){
SimpleDateFormat dt4 = new SimpleDateFormat("d_MMM_yy");
//Convert back into a string
VisitDate=dt4.format(date);
if(VisitDate==null){
SimpleDateFormat dt5 = new SimpleDateFormat("d_MMMM_yy");
//Convert back into a string
VisitDate=dt5.format(date);
if(VisitDate==null){
SimpleDateFormat dt6 = new SimpleDateFormat("dd_MMM_yy");
//Convert back into a string
VisitDate=dt6.format(date);
if(VisitDate==null){
SimpleDateFormat dt7 = new SimpleDateFormat("dd_MMM_yyyy");
//Convert back into a string
VisitDate=dt7.format(date);
if(VisitDate==null){
SimpleDateFormat dt8 = new SimpleDateFormat("dd_MMMM_yyyy");
//Convert back into a string
VisitDate=dt8.format(date);
if(VisitDate==null){
VisitDate=VisitDate.replaceAll("\\s", "");
SimpleDateFormat dt9 = new SimpleDateFormat("dd MMMM yyyy");
//Convert back into a string
VisitDate=dt9.format(date);
}
}
}
}
}
}
}
}
} catch (Exception e) {
Logger.error(e+"->No visit Date frmo here with the original date as: "+date);
}
}
Happy to read your expressed interest in the modern date and time classes, here’s just a snippet to get you started:
String visitDate = " 5 April 2017 ";
DateTimeFormatter parseFormatter
= DateTimeFormatter.ofPattern("d MMMM uuuu", Locale.UK);
visitDate = visitDate.trim();
LocalDate date = LocalDate.parse(visitDate, parseFormatter);
// reformat to the string we like
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd_MM_uu");
visitDate = date.format(formatter);
The result is
05_04_17
I have spelled visitDate with a small v since the Java coding conventions recommend that variable names begin with a small letter.
The uu is subtle and probably something you can ignore. It’s a signed year where 0 equals 1 BC, -1 equals 2 BC and so forth. Assuming none of your dates are that old, you can use u and y interchangeably.
I believe that neither SimpleDateFormat.format() nor LocalDate.format() will ever return null, so all your null checks are superfluous.
Link for further reading: Oracle tutorial: Trail: Date Time
You only have one SimpleDateFormatter being used for parsing:
SimpleDateFormat changeDate = new SimpleDateFormat("dd_MMM_yy", Locale.UK);
//Convert the string to a date
Date date = changeDate.parse(VisitDate);
It is using the format dd_MMM_yy, however you are passing 4 digits for the year.
The rest of your SimpleDateFormatters are being used for formatting to a string, not parsing from a string. Only the first one will be called, since it will be able to produce a string given a valid date, and the following null checks will stop any other formatters from being used.
You have the input string to parse like this: " 5 April 2017 ". But you have no pattern match for this input
First please trim the space of input string
Second please change the format of your string or add another pattern to parse this string, because you have month April with 5 letter, but you have no pattern with MMMMM. Usually the month will be shorten to 3 letter like: April -> Apr, March -> Mar ...
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
Code
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Date today = df.parse("20-12-2005 23:59:59");
System.out.println("Today = " + df.format(today));
} catch (ParseException e) {
e.printStackTrace();
}
Output
20-12-2005 23:59:59
But it's string object I want the same output (20-12-2005 23:59:59) as date object not as string object.
How can I get the Date in the form DD-MM-YYYY HH:MM:SS?
Date today is the date object you get for input String. There are nothing like formatted dates in Java. Date is always just date object. You perform all sorts of operations on that date object and when you want to Store (or) display just apply format()
df.format(today) // is just for formatting and display purpose.
There is difference in your format passed to SimpleDateFormat and way you are passing date string. You should Also use HH
DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
try {
Date today = df.parse("20-12-2005 23:59:59");
System.out.println("Today = " + df.format(today));
//To Print Real Today
System.out.println("Real Today = " + df.format(new Date()));
} catch (ParseException e) {
e.printStackTrace();
}
The Date class has many deprecated methods and the only correct way to create it right now is via a long (read doc for details).
You should look into GregorialCalendar where you can pass some constant fields of Calendar as attributes.
If you want to input the date from your String, I would either do a custom parser that creates a calendar or something like this.
Hope I helped :)
My first attempt was:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
Date date = formatter.parse(string);
It throws ParseException, so I found this hack:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
TimeZone timeZone = TimeZone.getTimeZone("Etc/GMT");
formatter.setTimeZone(timeZone);
Date date = formatter.parse(string);
It did not work either, and now I'm stuck. It parses without problems if I just change the timezone to "GMT".
edit: An example string to parse would be "2011-11-29 10:40:24 Etc/GMT"
edit2: I would prefer not to remove timezone information completely. I am coding a server that receives the date from an external user, so perhaps other dates will have other timezones.
To be more precise: This specific date I receive is from the receipt from the apple server after making an in app purchase on an iphone app, but I could also receive dates from other sources.
Don't know if this question is still relevant to you, but if you use Joda time, this'll work:
DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss ZZZ").parseDateTime(s)
Without Joda time the following will work (bit more work though):
String s = "2011-11-29 10:40:24 Etc/GMT";
// split the input in a date and a timezone part
int lastSpaceIndex = s.lastIndexOf(' ');
String dateString = s.substring(0, lastSpaceIndex);
String timeZoneString = s.substring(lastSpaceIndex + 1);
// convert the timezone to an actual TimeZone object
// and feed that to the formatter
TimeZone zone = TimeZone.getTimeZone(timeZoneString);
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatter.setTimeZone(zone);
// parse the timezoneless part
Date date = formatter.parse(dateString);
It didn't work for me either the thing is I tried setting TimeZone of SimpleDateFormatter to "Etc/GMT" and then formatted a new date here is the output:
2011-11-30 10:46:32 GMT+00:00
So Etc/GMT is being translated as GMT+00:00
If you really want to stick to parse "2011-09-02 10:26:35 Etc/GMT" then following will help too without even considering explicit Timezone change:
java.text.SimpleDateFormat isoFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss 'Etc/GMT'");
isoFormat.parse("2010-05-23 09:01:02 Etc/GMT");
Works fine.
Following code is working for me
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("Etc/GMT"));
try { System.out.println( sdf.parse("2011-09-02 10:26:35 Etc/GMT") );
} catch (ParseException e){
e.printStackTrace();
}
I'm having a hard time Parsing/Formatting a Date string received back from a web service. I've attempted multiple approaches, but with no luck.
Sample Date String:
2011-10-05T03:00:00Z
Exception:
W/System.err(10072): java.text.ParseException: Unparseable date: "2011-10-05T05:00:00Z" (at offset 10)
W/System.err(10072): at java.text.DateFormat.parse(DateFormat.java:626)
Sample Code:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:SSSS");
Date date = formatter.parse(info.AiringTime);
I've found that if I remove the "T" between the date and the time and replace it with a space, it will format just fine. Anybody have any suggestions?
--UPDATE--
After looking deeper into the API documentation, I found this:
All response DateTime values are in UTC format. You need to apply the UTC offset to calculate the local time for display.
DateTime is a date-and-time value specified in one of the following formats:
UTC format: YYYY-MM-DDThh:mm:ssZ. For example: 2011-03-15T02:00:00Z.
Local time with an offset: YYYY-MM-DDThh:mm:ss + or - hh:mm (positive or negative offset). For example, for US Pacific time: 2011-03-14T06:00:00 -08:00.
Any suggestions on the UTC format approach?
You could try:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateString = dateString.replace("Z", "GMT+00:00");
Date date = dateFormat.parse(dateString);
The above code should correctly handle the case where a timezone is specified in the date. As Z represents the UTC/GMT timezone it is replaced by GMT so the SimpleDateFormat can interpret it correctly (i would love to know a cleaner way of handling this bit if anyone knows one).
Try,
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
This pattern should parse the date you provide: "yyyy-MM-dd'T'HH:mm:ss'Z'".
If you want to use SimpleDateFormat and you have a limited number of variations, you can create separate formatters for each pattern and chain them:
Date date = formatter1.parse(info.AiringTime);
if (date == null)
{
date = formatter2.parse(info.AiringTime);
if (date == null)
{
date = formatter2.parse(info.AiringTime);
if (date == null)
{
date = formatter3.parse(info.AiringTime);
}
}
}
or put them in a list and iterate until non-null or no more formatters.
If you have too many patterns for this to be practical, you can parse it yourself or try one of these libraries.
This worked for me
SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss'Z'");
SimpleDateFormat viewFriendlyDateFormat = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss aaa");
String viewFriendlyDate = "";
try {
Date date = isoDateFormat.parse(timestamp);
viewFriendlyDate = viewFriendlyDateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss'Z'");
SimpleDateFormat viewFriendlyDateFormat = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss aaa");
String viewFriendlyDate = "";
try {
Date date = isoDateFormat.parse(timestamp);
viewFriendlyDate = viewFriendlyDateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}