SimpleDateFormat print "." for MMM format - java

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

Related

How to convert date from mm/dd/yyyy to mm dd, yyyy

I want to convert date from 07/02/2019 to July 07, 2019. My input value is 07/02/2019 I want to compare with target value July 07, 2019....Please help me on this...
public static void main(String[] args) throws ParseException {
String sDate1="07/01/2019";
java.util.Date date1=new SimpleDateFormat("MM/dd/yyyy").parse(sDate1);
System.out.println(date1);
Output:Mon Jul 01 00:00:00 IST 2019 which is not my expected value
Try this one.
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
SimpleDateFormat output = new SimpleDateFormat("MMMM dd, yyyy");
Date data = sdf.parse("07/02/2019");
String newDate = output.format(data);
System.out.println(newDate);
Here, you use:
java.util.Date date1=new SimpleDateFormat("MM/dd/yyyy").parse(sDate1);
to parse a date that comes in as String.
Then you print that date without any formatting information.
Thus the answer is quite simple: define a pattern for formatting a Date object as string! Same rules, same patterns. Just not parsing, but formatting for printing!
In other words: you already know the concept, you used a formatter to turn a String into a Date. Now simply turn that around, and provide a pattern to a formatter to turn a Date into a string!
Parse your input date
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
LocalDate date = LocalDate.parse(sDate, formatter);
Similarly parse your target date
DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern("MMMM dd, uuuu", Locale.ENGLISH);
LocalDate targetDate = LocalDate.parse("July 07, 2019");
Or better yet, define your target date without using a string
LocalDate targetDate = LocalDate.of(2019, Month.JULY, 7);
Compare
if (date.equals(targetDate)) {
System.out.println("Same date");
}
LocalDate also have methods isBefore and isAfter.
This answer is entered from my tablet without trying the code out, so please forgive the typos.

Is the following DateFormat able to generate locale indepdent date string

My ideal way, of having a locale independent date string, is by using the following code
DateFormat dateFormat = new SimpleDateFormat("MMM d, yyyy", Locale.ENGLISH);
which means, if I run the above code in a Arabic device, or a United States device, both will generate same string.
For the above case, dateFormat.format(date) will produce Dec 26, 2015.
I came across a legacy code, which is using the following way to generate locale independent date string.
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.ENGLISH);
Will the above code be truly locale independent. Will it "mistakenly" generate string like 26 Dec, 2015?
I wrote a simple code, to test both on Windows and Android device.
for (Locale locale : Locale.getAvailableLocales()) {
Locale.setDefault(locale);
DateFormat dateFormat0 = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.ENGLISH);
DateFormat dateFormat1 = new SimpleDateFormat("MMM d, yyyy", Locale.ENGLISH);
if (false == dateFormat0.format(date).equals(dateFormat1.format(date))) {
throw new java.lang.RuntimeException("Opps");
}
}
No exception was being thrown.
I was wondering, can we assume that DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.ENGLISH) will generate same date string too across different devices? Is there any edge case I didn't handle?
Using "MMM dd, yyyy"you retain control of the output, where by using the integer constant DateFormat.DEFAULT you are leaving it up to the locale definitions for the platform. They should be identical across these platforms for any given locale, but there really are no guarantee.
The DateFormat.DEFAULT parameter is only useful if you work with different Locales, as it'll allow DateFormat to create the proper localized date string.
Example:
DateFormat dfEn = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.ENGLISH);
DateFormat dfFr = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.FRENCH);
DateFormat dfGe = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.GERMAN);
System.out.println("ENGLISH: " + dfEn.format(date));
System.out.println("FRENCH : " + dfFr.format(date));
System.out.println("GERMAN : " + dfGe.format(date));
prints:
ENGLISH: Dec 26, 2015
FRENCH : 26 déc. 2015
GERMAN : 26.12.2015
I you want to be sure that the rendered date looks always the same it's the best choice to define the format explicitely as you did in your first code snippet:
DateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy", Locale.ENGLISH);
The given locale here does not define the formatting but the wording to be used, here the name of the month is in english ("Dec"), rather than e.g. in german ("Dez").

SimpleDateFormat and parseException

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!!!

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

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