Java DateTime parse - java

I have the following code to simply parse a date and time to a format
SimpleDateFormat sdfClient = new SimpleDateFormat("yyyyMMddhhmmss.s");
SimpleDateFormat sdfFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
pmList.add(sdfClient.format(sdfFormat.parse(pmData[k].retrievalTime)));
Wanna change the format to sdfClient but for some reason eclipse throws an error:
java.text.ParseException: Unparseable date: "20140623135000.0"
at java.text.DateFormat.parse(DateFormat.java:357)
at com.syntronic.client.GenerateCSV.writepmData(GenerateCSV.java:220)
at com.syntronic.client.GenerateCSV.writeMEData(GenerateCSV.java:187)
at com.syntronic.client.GenerateCSV.<init>(GenerateCSV.java:87)
at com.syntronic.client.Client.main(Client.java:213)
Anyone knows the reason why?

It should be just the other way around:
pmList.add(sdfFormat.format(sdfClient.parse(pmData[k].retrievalTime)));
Explanation:
pmList.add(
sdfFormat.format( <-- Gives a string 23/06/2014 01:50:00
sdfClient.parse( <-- Gives a Date corresponding to the time 20140623135000.0
pmData[k].retrievalTime <-- Time 20140623135000.0
)
)
);

You've got your formatter and parser mixed about
pmList.add(sdfClient.format(sdfFormat.parse(pmData[k].retrievalTime)));
Basically says, "yyyyMMddhhmmss.s".format("dd/MM/yyyy hh:mm:ss".parse(...))
You want to use
pmList.add(sdfFormat.format(sdfClient.parse(pmData[k].retrievalTime)));
Instead...

Related

Date value converted from Calendar outputs different format than String [duplicate]

I have the following scenario :
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.parse("31/05/2011"));
gives an output
Tue May 31 00:00:00 SGT 2011
but I want the output to be
31/05/2011
I need to use parse here because the dates need to be sorted as Dates and not as String.
Any ideas ??
How about:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")));
> 31/05/2011
You need to go through SimpleDateFormat.format in order to format the date as a string.
Here's an example that goes from String -> Date -> String.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("31/05/2011");
System.out.println(dateFormat.format(date)); // prints 31/05/2011
// ^^^^^^
Use the SimpleDateFormat.format
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String sDate= sdf.format(date);
You can use simple date format in Java using the code below
SimpleDateFormat simpledatafo = new SimpleDateFormat("dd/MM/yyyy");
Date newDate = new Date();
String expectedDate= simpledatafo.format(newDate);
It makes no sense, but:
System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")))
SimpleDateFormat.parse() = // parse Date from String
SimpleDateFormat.format() = // format Date into String
If you want to simply output a date, just use the following:
System.out.printf("Date: %1$te/%1$tm/%1$tY at %1$tH:%1$tM:%1$tS%n", new Date());
As seen here. Or if you want to get the value into a String (for SQL building, for example) you can use:
String formattedDate = String.format("%1$te/%1$tm/%1$tY", new Date());
You can also customize your output by following the Java API on Date/Time conversions.
java.time
Here’s the modern answer.
DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
DateTimeFormatter displayFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.forLanguageTag("zh-SG"));
String dateString = "31/05/2011";
LocalDate date = LocalDate.parse(dateString, sourceFormatter);
System.out.println(date.format(displayFormatter));
Output from this snippet is:
31/05/11
See if you can live with the 2-digit year. Or use FormatStyle.MEDIUM to obtain 2011年5月31日. I recommend you use Java’s built-in date and time formats when you can. It’s easier and lends itself very well to internationalization.
If you need the exact format you gave, just use the source formatter as display formatter too:
System.out.println(date.format(sourceFormatter));
31/05/2011
I recommend you don’t use SimpleDateFormat. It’s notoriously troublesome and long outdated. Instead I use java.time, the modern Java date and time API.
To obtain a specific format you need to format the parsed date back into a string. Netiher an old-fashioned Date nor a modern LocalDatecan have a format in it.
Link: Oracle tutorial: Date Time explaining how to use java.time.
You already has this (that's what you entered) parse will parse a date into a giving format and print the full date object (toString).
This will help you.
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
print (df.format(new Date());
I had something like this, my suggestion would be to use java for things like this, don't put in boilerplate code
This looks more compact. Finishes in a single line.
import org.apache.commons.lang3.time.DateFormatUtils;
System.out.println(DateFormatUtils.format(newDate, "yyyy-MM-dd HH:mm:ss"));

How to get Timestamp with AM/PM in java

I have a date as String , which needs to be converted in to Time Stamp with AM/PM . I tried the below way, I'm getting the proper date format but didn't get in AM/PM.
Can any one please help ?
code Snippet:
String dateString = "10/10/2010 11:23:29 AM";
SimpleDateFormat sfdate = new SimpleDateFormat("MM/dd/yyy HH:mm:ss a");
Date date = new Date();
date = sfdate.parse(dateString);
System.out.println(new Timestamp(date.getTime()));
Which gives me the output as below :
2010-10-10 11:23:29.0
But I needs it like this
2010-10-10 11:23:29.00000000 AM
Kindly help me please.
Why create a timestamp ? When you can just :
SimpleDateFormat sfdate = new SimpleDateFormat("MM/dd/yyy HH:mm:ss a");
Date date = new Date();
date = sfdate.parse(dateString);
System.out.println(sfdate.format(date) );
Output:
10/10/10 11:23:29 AM
Try:
System.out.println(sfdate.format(date));
As your last line rather than the one that you have at current.
Timestamp.toString() prints to a specific format: yyyy-mm-dd hh:mm:ss.fffffffff. The Timestamp object itself should be correct, if that's all you are looking for.
If you then want to define another format in order to print it as you like, that would require you to format Date object, using an appropriate pattern for the output format you are looking for.
What you're seeing is the result of Timestamp.toString(). The actual value in the Timestamp object instance is valid.
If you're getting an error in a subsequent SQL operation, please post that error along with the code you're using.

SimpleDateFormat ParseException : Unparseable date

I'm trying to execute this code:
Date date = null;
if (detailsBean.getDiscoveryProjectBean ().getCreatedDate ()==null ||
detailsBean.getDiscoveryProjectBean ().getCreatedDate ().equalsIgnoreCase(""))
{
projectDetails.getDiscoveryProject().setCreationTime(new Date());
}
else
{
try
{
date = new SimpleDateFormat (FormatUtils.simpleFormat).
parse (detailsBean.getDiscoveryProjectBean ().getCreatedDate ());
} catch (Exception e) {
throw new PanDaApplicationException (e.getMessage ());
}
projectDetails.getDiscoveryProject().setCreationTime(date);
}
in the try block a ParseException exception is thrown. I don't know the cause of that as the code seems fine, however. the definition of the FormatUtils.simpleFormat is public static final String simpleFormat = "dd-MMM-yyyy" and detailsBean.getDiscoveryProjectBean().getCreatedDate() have value like 28-Feb-2013
I really don't have any clues why this exception is thrown and I need help.
My guess is that the problem is the way that SimpleDateFormat uses your default locale - if your locale doesn't use "Feb" as an abbreviated month name, you'll have problems. So if all your data is actually in English, you might want:
DateFormat format = new SimpleDateFormat(FormatUtils.simpleFormat, Locale.US);
format.setTimeZone(...); // See below
date = format.parse(detailsBean.getDiscoveryProjectBean().getCreatedDate());
Note the part about setting the time zone. Again, SimpleDateFormat will use your system default if you don't specify anything else. (You'll get the instant of "midnight in the specified time zone" as the Date value.)
I would also strongly urge you to consider using Joda Time instead of the built-in Date/Calendar types - it's a much better date/time API.
Locale.setDefault (Locale.ROOT);
System.out.println (new SimpleDateFormat ("dd-MMM-yyyy").parse ("28-Feb-2013"));
Locale.setDefault (Locale.forLanguageTag ("ru"));
System.out.println (new SimpleDateFormat ("dd-MMM-yyyy").parse ("28-Feb-2013"));
For me output is:
Thu Feb 28 00:00:00 MSK 2013
Exception in thread "main" java.text.ParseException: Unparseable date: "28-Feb-2013"
at java.text.DateFormat.parse(DateFormat.java:357)
at DateFormat.main(DateFormat.java:19)
So the same date successfully parsed with ROOT locale, but failed with Russian.

java : java.text.ParseException: Unparseable date

I am reciving a input in this format 2012-01-13T00:00:00.000-05:00 and which i need to convert this into yyyyMMdd Format .
I have also set the SimpleDateFormat.setLenient(false);
This is my coding for parsing the Date
public static String getparsedDate(String date) throws Exception {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
sdf.setLenient(false);
String s1 = date;
String s2 = null;
Date d;
try {
d = sdf.parse(s1);
s2 = (new SimpleDateFormat("yyyyMMdd")).format(d);
} catch (ParseException e) {
e.printStackTrace();
}
return s2;
}
But i am getting a Exception at
java.text.ParseException: Unparseable date: "201201"
at java.text.DateFormat.parse(Unknown Source)
Could anybody please let me know , what might be the issue ?
You are missing the timezone in your format string. If you check the argument, it is finishing with -05:00 and you are also using Lenient==false.
Unfortunately, the time zone formats available to SimpleDateFormat are not ISO8601 compliant. SimpleDateFormat understands time zone strings like "GMT+01:00" or "+0100", the latter according to RFC822. Therefore using SimpleDateFormat does not seem as an option in your case (since you use UTC−05:00 as timezone).
Instead of SimpleDateFormat you need to use JodaTime for that type of date format.

SimpleDateFormat ParseException: Unparseable date Error

I'm parsing this date format from XML:=> "2011-12-06T07:41:14.016+00:00", and I'm getting this error:
W/System.err(574): java.text.ParseException: Unparseable date:
"2011-12-06T07:41:14.016+00:00"
I'm certain it's the formatting statement I'm using, but I can't figure out what it SHOULD be...
Here's the statement I'm using:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ:ss");
I get how to create a format for this part: "2011-12-06T07:41:14....", it's this other part :=> ".016+00:00" that's throwing me for a loop.
I've looked for answers here already: Android SimpleDateFormat Page, and here Oracle SimpleDateFormat Page, but I fear I'm missing something fundamental....
Do you have any suggestions on a proper format statement for that particular date format, or pertinent resources to peruse?
Big Thanks in advance!
The "Z" pattern matches +0000 and not +00:00 so if you remove the last ":" before you parse then it will work.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ");
try {
Date myDate = sdf.parse( "2011-12-06T07:41:14.016+00:00".replaceAll( "([0-9\\-T]+:[0-9]{2}:[0-9.+]+):([0-9]{2})", "$1$2" ) );
System.out.println( myDate );
} catch (ParseException e) {
e.printStackTrace();
}
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" 2001-07-04T12:08:56.235-0700
The :ss at the end looks incorrect
As one of the answers in the question I linked shows, you can use
String string = "2011-12-06T07:41:14.016+00:00";
Calendar cal = DatatypeConverter.parseDateTime(string);
What's the best way to parse an XML dateTime in Java?

Categories

Resources