SimpleDateFormat and parseException - java

I am developing a Web application into GWT and I am using the Object DatePicker. This object retrieves the date in a defined format which I am translating into a String such as:
Wed May 14 2014 00:00
For me it is useful to use this date as String for some operations. However, for one of them I need the Timestamp object. For that reason, I am making use of the SimpleDateFormat object in the following way:
SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd yyyy HH:mm");
Timestamp tDateIni = new Timestamp(sdf.parse(sDateIni).getTime());
Yet, when I run the remote debug I get a ParseException. Do you know what could the mistake be? I think I am using in a bad format the SimpleDateFormat object in the part "E MMM", but I am not sure. Thanks a lot in advance!

If you want to parse the date at client side in GWT then try with DateTimeFormat
DateTimeFormat dateTimeFormat=DateTimeFormat.getFormat("E MMM dd yyyy HH:mm");
Date date=dateTimeFormat.parse("Wed May 14 2014 00:00");
If you want to parse the date at server side then pass the time in milliseconds as long value instead of date string from client side and form the date back at server side using new Date(timeInMills)

Your date format uses the day of the week format that requires "EEE" instead of "E". This is causing the exception when the program is trying to read in your date string. It is expecting one letter for the day of the week.
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Change this from
SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd yyyy HH:mm");
to
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm");
It should be EEE instead of E to represent Weekdays like Wed
Below code, perfectly works (TESTED)
public static void main(String[] args) {
String s = "Wed May 14 2014 00:00";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm");
try {
Timestamp tDateIni = new Timestamp(sdf.parse(s).getTime());
System.out.println(tDateIni.getTime());
} catch (ParseException ex) {
System.out.println("Parse Error");
}
}

I have added the Locale object in the SimpleDateFormat object and now it works. Thank you for all your help and your comments!!!

Related

SimpleDateFormat print "." for MMM format

I am trying to convert date string from one format to another using SimpleDateFormat.
Conversion works but there is a dot "." after month.
String dateStr = "04/02/1987";
DateFormat df1 = new SimpleDateFormat("dd/MM/yyyy");
Date d = df1.parse(dateStr);
DateFormat df2 = new SimpleDateFormat("dd MMM yyyy");
System.out.println(df2.format(d));
Output is 04 Feb. 1987 instead of 04 Feb 1987.
What is your Locale.getDefault()?
Different output for alphanumeric date parts may be caused by the Locale the formatter is using. In most cases, the system default Locale is used if you don't specify one yourself. I don't know for sure SimpleDateFormat does so, but it seems likely.
I know that a java.time.format.DateTimeFormatter does so, see the following example which uses java.time, the modern and recommended to use datetime API:
public static void main(String[] args) {
String dateStr = "04/02/1987";
LocalDate localDate = LocalDate.parse(dateStr, DateTimeFormatter.ofPattern("dd/MM/yyyy"));
System.out.println(localDate.format(DateTimeFormatter.ofPattern("dd MMM yyyy",
Locale.ENGLISH)));
System.out.println(localDate.format(DateTimeFormatter.ofPattern("dd MMM yyyy",
Locale.FRENCH)));
}
Output:
04 Feb 1987
04 févr. 1987
The output is (of course) different concerning the name of the month, but using Locale.FRENCH shows a dot after the abbreviated month name. It is possible that your system's default Locale is one that indicates an abbreviation by a dot, too, but is identical to the output format of a Locale.ENGLISH for the numeric parts and the abbreviation of the month.
Please provide Locale.ENGLISH in SimpleDateFormat constructor while creating object as shown below:
String dateStr = "04/02/1987";
DateFormat df1 = new SimpleDateFormat("dd/MM/yyyy");
Date d = df1.parse(dateStr);
DateFormat df2 = new SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH);
System.out.println(df2.format(d));

I am getting java.text.ParseException

In the below code getting parsing error:please help.
DateFormat converter = new SimpleDateFormat("dd/MM/yyyy:HH:mm:ss");
converter.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat formatter = new SimpleDateFormat("E, MMM dd yyyy");
Date date = formatter.parse(converter.format(new Date()));
I will try to explain what JB Nizet and others tried in the comments. In a simplified manner to make it understandable.
A Date is nothing else but a long which represents the time since epoch and a nice toString() method. Basically.
So if you create a Date date = new Date(); it sets the date's time value to System.currentTimeMillis();, nothing more, nothing less.
The interesting thing is that the Unix time is already "in UTC (=GMT)", if you want to say so.
If you now print the date like this
Date date = new Date();
System.out.println(date);
you implicitly call date.toString();.
This toString() can be seen as follows:
public String toString() {
return new SimpleDateFormat("E MMM dd HH:mm:ss z YYYY").format(this);
}
The SimpleDateFormat uses by default YOUR timezone. But it doesn't change the value of the date at all, it just prints it in another way.
If you now want to see the date in GMT you can simply set the SimpleDateFormat yourself:
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd HH:mm:ss z YYYY");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf.format(date));
To push it further you could now write a simple static method somewhere to print dates in specific timezones:
public static void printDate(Date date) {
printDate(date, "GMT");
}
public static void printDate(Date date, String timeZone) {
printDate(date, TimeZone.getTimeZone(timeZone));
}
public static void printDate(Date date, TimeZone timeZone) {
SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd HH:mm:ss z YYYY");
sdf.setTimeZone(timeZone);
System.out.println(sdf.format(date));
}
To see what we all are talking about (that the timestamp does never change) you can print both:
public static void printDate(Date date, TimeZone timeZone) {
SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd HH:mm:ss z YYYY");
sdf.setTimeZone(timeZone);
System.out.println(sdf.format(date) + " has the timestamp " + date.getTime());
}
If we now do some simple tests we see these results:
Local Time:
Sat Feb 22 16:08:12 CET 2014 has the timestamp 1393081692749
GMT:
Sat Feb 22 15:08:12 GMT 2014 has the timestamp 1393081692749
PST:
Sat Feb 22 07:08:12 PST 2014 has the timestamp 1393081692749
As you can see the times are all correct for their timezones, and the timestamp itself is always the same.
So to answer your question: Your simple new Date();, as it's already written in the comments, already achieves what you want: the Date is always in UTC (which equals GMT).

Java DateTime format for this one

What is the Java DateTime format for this one?
Mon Nov 26 13:57:03 SGT 2012
I want to convert this string to Date and convert it to another format like "yyyy-MM-dd HH:mm:ss".
To convert from date to string is not hard.
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
But I find no valid format to convert "Mon Nov 26 13:57:03 SGT 2012" to become date format...
=====
found solution:
DateFormat oldDateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Format newDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date oldDate = oldDateFormat.parse(oldTimeString);
String newDateString = newDateFormat.format(oldDate);
This will work, EEE MMM dd HH:mm:ss z yyyy
You can find examples in the javadoc of SimpleDateFormat. See http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
Try SimpleDateFormat.parse() function to convert the string to Date.
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date parseDate = sdf.parse(strInput);
Watch out for the Parse Exception
Well, this code produces some output
import java.util.*;
import java.text.*;
public class Test {
public static void main(String[] args) throws ParseException {
DateFormat inputFormat = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy",
Locale.US);
DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
Locale.US);
String text = "Mon Nov 26 13:57:03 SGT 2012";
Date date = inputFormat.parse(text);
System.out.println(outputFormat.format(date));
}
}
... but it uses the default system time zone for output. It's not clear what time zone you want the result in. There's nothing in Date to store the time zone, which makes it hard to preserve the original time zone given in the text, so you'll need to decide for yourself which zone to use.
Note that I've specified Locale.US in both input and output; that's typically appropriate when you're specifying a custom format, particularly for the input which relies on month and day names.
As noted in comments, I would personally recommend using Joda Time if you possibly can for date/time work... it's a far better API than Date/Calendar. Unfortunately, Joda Time is incapable of parsing time zones - from the docs for DateTimeFormat:
Zone names: Time zone names ('z') cannot be parsed.
It's also worth noting that if there's any way you can affect the input data, moving them away from using time zone abbreviations would be a good step.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CPDateTime
{
public static void main(String[] args)
{
Calendar cal = Calendar.getInstance();
//subtracting a day
//cal.add(Calendar.DATE, -1);
cal.add(Calendar.MONTH, -1);
SimpleDateFormat prev_day = new SimpleDateFormat("dd");
SimpleDateFormat prev_month = new SimpleDateFormat("MM");
SimpleDateFormat prev_year = new SimpleDateFormat("YYYY");
String prev_day_str = prev_day.format(new Date(cal.getTimeInMillis()));
System.out.println(prev_day_str);
String prev_month_str = prev_month.format(new Date(cal.getTimeInMillis()));
System.out.println(prev_month_str);
String prev_year_str = prev_year.format(new Date(cal.getTimeInMillis()));
System.out.println(prev_year_str);
}
}

the exception with parsing a date YYYY-MM-DD HH:mm:ss

I try to parse a date in the format YYYY-MM-DD HH:mm:ss
String now = "2012-11-02 12:02:00";
DateFormat formatter;
formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date date_temp = (Date) formatter.parse(now.toString());
System.out.println("output: " + date_temp);
It gives me following exception
java.text.ParseException: Unparseable date: "2012-11-02 12:02:00"
Well yes, you've created a formatted with one format ("EEE MMM dd HH:mm:ss z yyyy") and then given it a string in a completely different format to parse. Why did you think that would work? Try this:
// Locale specified to avoid any cultural differences. You may also
// want to specify the time zone.
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
Locale.US);
Date date = formatter.parse(now);
Note that the parsed Date does not know anything about formatting - the result of calling toString() (as you're doing implicitly here) is always just the default format, in the JRE default time zone. If you want to print it out with a particular format, use SimpleDateFormat again.
Also note that I've combined declaration and initialization for the variable. Prefer that over declaring a variable in one line and giving it an initial value later.
Of course your date string is not in the format you are using in SimpleDateFormat. So it won't be able to parse it into a date object.
Try using this: -
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

DATETIME convert

can anyone help me with converting DATETIME funtction in Java.
I retrieve the date time format from SMS headers in this format "Fri May 18 09:22:39 FJT 2012" .I want to convert it to this format "2012-05-18 09:51:42.39".Can anyone help.
Use a SimpleDateFormat for that purpose. Although I am not sure that the timezone "FJT" is known in Java. So you will maybe have to do some tricks for that.
As #Guillaume suggested, use SimpleDateFormat. Here's an example:
public String convert() throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
Date output = format.parse("Fri May 18 09:22:39 FJT 2012");
Calendar outputCal = Calendar.getInstance(format.getTimeZone());
outputCal.setTime(output);
return String.format("%04d-%02d-%02d %02d:%02d:%02d",outputCal.get(Calendar.YEAR), outputCal.get(Calendar.MONTH)+1, outputCal.get(Calendar.DAY_OF_MONTH), outputCal.get(Calendar.HOUR_OF_DAY), outputCal.get(Calendar.MINUTE), outputCal.get(Calendar.SECOND));
}
Everything is hardcoded - you have to add parameters as necessary
import java.text.SimpleDateFormat;
...
String d = "Fri May 18 09:22:39 FJT 2012";
SimpleDateFormat inputFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss ZZZ yyyy");
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SS");
outputFormat.setTimeZone(TimeZone.getTimeZone("GMT")); // set yr time zone for output
Date date = inputFormat.parse(d);
System.out.println(outputFormat.format(date));

Categories