date format in java - java

My requirement is to get the date in format MM/dd/yy. But I am currently getting the date value as "Sun Dec 31 00:00:00 IST 2006". I tried a sample code for the conversion as follows.
String pattern = "MM/dd/yyyy";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
Date date = format.parse("12/31/2006");
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
Please help me to convert the given date into MM/dd/yy

You need to use SDF (SimpleDateFormat) to process the output too.
String pattern = "MM/dd/yyyy";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
Date date = format.parse("12/31/2006");
System.out.println(format.format(date));
} catch (ParseException e) {
e.printStackTrace();
}

Change your code to:
String pattern = ;
SimpleDateFormat inputFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat outputFormat = new SimpleDateFormat("MM/dd/yy");
try {
Date date = inputFormat.parse("12/31/2006");
System.out.println(outputFormat.format(date));
} catch (ParseException e) {
e.printStackTrace();
}

The reason of your output is because you're outputting the date object through System.out.println(date); which is effectively, translated to System.out.println(date.toString());
The toString() method of Date outputs date in the format of:
EEE MMM dd HH:mm:ss zzz yyyy
Here's the code for Date.toString()
public String toString() {
// "EEE MMM dd HH:mm:ss zzz yyyy";
BaseCalendar.Date date = normalize();
StringBuilder sb = new StringBuilder(28);
int index = date.getDayOfWeek();
if (index == gcal.SUNDAY) {
index = 8;
}
convertToAbbr(sb, wtb[index]).append(' '); // EEE
convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' '); // MMM
CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd
CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':'); // HH
CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
TimeZone zi = date.getZone();
if (zi != null) {
sb.append(zi.getDisplayName(date.isDaylightTime(), zi.SHORT, Locale.US)); // zzz
} else {
sb.append("GMT");
}
sb.append(' ').append(date.getYear()); // yyyy
return sb.toString();
}
Your code is correct though. Use SimpleDateFormat to display the date like so:
System.out.println(format.format(date));

You're using the SimpleDateFormat to parse a string, and that's working fine - but then you're using Date's toString method (implicitly) when formatting the date. That will use a default format which is completely independent of the format which was originally used to parse the value.
A Date object knows nothing about how you want to format it. That's what you should be using SimpleDateFormat for.
You can use SimpleDateFormat to format it again:
System.out.println(format.format(date));
... but a better approach would be to switch to Joda Time and use its DateTimeFormatter class, which is thread-safe and immutable, unlike SimpleDateFormat... the rest of its API is better, too.

Related

Convert String to Date with Milliseconds

I know that there many subject of how to convert from String to Date, I'm using 'SimpleDateFormat' and i have a string that contains (Year, Month, Day , Hour, Minute, second, Milliseconds) but when I'm using the 'SimpleDateFormat' the Milliseconds is not set
here the code and the output:
import java.text.SimpleDateFormat;
import java.util.Date;
String strDate = "2020-08-27T10:06:07.413";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date dateFormatter = formatter.parse(strDate);
System.out.println(dateFormatter);
Output:
Thu Aug 27 10:06:07 WAT 2020
I want the result in type Date
The Date class stores the time as milliseconds, and if you look into your date object you will see that it actually has a time of 1598515567413 milliseconds.
You are fooled by the System.out.println() which uses Date's toString() method. This method is using the "EEE MMM dd HH:mm:ss zzz yyyy" format to display the date and simply omits all milliseconds.
If you use your formatter, which has milliseconds in its format string, you will see that the milliseconds are correct:
System.out.println(formatter.format(dateFormatter));
outputs 2020-08-27T10:06:07.413
You can use:
String strDate = "2020-08-27T10:06:07.413"
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
DateTime datetimeDF = formatter.parseDateTime(strDate);
String text = formatter.print(datetimeDF);
System.out.println(text);
Or you can use java.time:
String strDate = "2020-08-27T10:06:07.413"
LocalDateTime ldate = LocalDateTime.parse(datetime, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS"));
and use the object ldate as you want.
Update (based on OP's comment):
You have mentioned: Thanks that was realy heplful I've allready tried the java.util but i could not set the date in the database using LocalDateTime that's why I'm using Date
You've to use PreparedStatement#setObject to set LocalDate into the database table e.g.
LocalDate localDate = LocalDate.now();
PreparedStatement st = conn.prepareStatement("INSERT INTO mytable (columnfoo) VALUES (?)");
st.setObject(1, localDate);
st.executeUpdate();
st.close();
Original answer:
Given below is the toString implementation of java.util.Date:
public String toString() {
// "EEE MMM dd HH:mm:ss zzz yyyy";
BaseCalendar.Date date = normalize();
StringBuilder sb = new StringBuilder(28);
int index = date.getDayOfWeek();
if (index == BaseCalendar.SUNDAY) {
index = 8;
}
convertToAbbr(sb, wtb[index]).append(' '); // EEE
convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' '); // MMM
CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd
CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':'); // HH
CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
TimeZone zi = date.getZone();
if (zi != null) {
sb.append(zi.getDisplayName(date.isDaylightTime(), TimeZone.SHORT, Locale.US)); // zzz
} else {
sb.append("GMT");
}
sb.append(' ').append(date.getYear()); // yyyy
return sb.toString();
}
As you can see in this implementation, it doesn't include milliseconds and therefore if you print date as in the following code, you will get what the Date#toString returns and thus, you won't see milliseconds in the output.
String strDate = "2020-08-27T10:06:07.413";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date date= formatter.parse(strDate);
System.out.println(date);
I assume that you already know that System.out.println(obj) prints the string returned by obj.toString().
How can you get output in a custom format?
You have two options:
Recommended option: Use a date-time formatter e.g. SimpleDateFormat as shown below:
String strDate = "2020-08-27T10:06:07.413";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date date = formatter.parse(strDate);
System.out.println(date);
String dateStr = formatter.format(date);
System.out.println(dateStr);
Override toString implementation of Date by creating a custom class by extending java.util.Date. Although it's an option, I never recommend this to do.
Finally, a piece of advice:
Stop using the outdated and error-prone java.util date-time API and SimpleDateFormat. Switch to the modern java.time date-time API and the corresponding formatting API (java.time.format). Learn more about the modern date-time API from Trail: Date Time.

How can i get simple yyyy-MM-dd out of this date?

I have String with date format dd.MM.yyyy, and I want to upload it to my MS SQL server, but the required format is yyyy-MM-dd. I tried this but it doesn't work like I want to.
String expDate = mDatePickerBtn.getText().toString();
Date date = null;
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
try {
date = format.parse(expDate);
expDate = date.getYear() + "-" + date.getMonth() + "-" + date.getDay();
} catch (ParseException e) {
e.printStackTrace();
}
For example if I pass 31.12.2032 to the expDate, the date variable will cointain "Fri Dec 31 00:00:00: GMT+01:00 2032", and the expDate will contain "132-11-5" and I don't even know why.
I would use DateTimeFormatter but my minimal API level is 24.
My question is: where did I make mistake or how else can I get correct format out of this?
Go compile your app with Android Gradle Plugin 4.0.0+ and use java.time then like this:
public static void main(String[] args) {
// get / provide the String to be parsed
String expDate = "31.12.2032";
// provide a pattern that parses such a date
String pattern = "dd.MM.uuuu";
// create a DateTimeFormatter with this pattern
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
// parse the String with the DateTimeFormatter
LocalDate expLocalDate = LocalDate.parse(expDate, dtf);
// print the default format of a LocalDate
System.out.println(expLocalDate);
// print the LocalDate using the pattern created for parsing
System.out.println(expLocalDate.format(dtf));
// create a totally different DateTimeFormatter inline and format the date differently
System.out.println(expLocalDate.format(DateTimeFormatter.ofPattern("EEE, dd 'of' MMMM uuuu",
Locale.ENGLISH)));
}
The output would be this:
2032-12-31
31.12.2032
Fri, 31 of December 2032
Try this way
String expDate = mDatePickerBtn.getText().toString();
Date date = null;
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
try {
date = format.parse(expDate);
SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
format1.format(date);
expDate = format1.format(date);
} catch (ParseException e) {
e.printStackTrace();
}

Selecting Date format based on the string [duplicate]

This question already has an answer here:
Fri Mar 30 00:00:00 CET 14 to dd/mm/yyyy
(1 answer)
Closed 5 years ago.
I have class which receives Date in string format from other class. It is now receiving two different formats
Format 1: YYYY_MM_DD
Format 2: EEE MMM dd HH:mm:ss z yyyy
now I want to write a method which receives this string and convert it into required format like this 'DDMMMYYYY '
You can try brute force to parse catching the exceptions:
edit:
using the java8 API (adapt the format as you need/want)
public String convertDateFormatJ8(String format) {
String retFormat = "ddMMyyy";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("[yyyy_dd_MM][yyyy-MM-dd HH:mm]");
try {
LocalDateTime localDate = LocalDateTime.parse(format, formatter);
return localDate.format(DateTimeFormatter.ofPattern(retFormat));
} catch (DateTimeParseException ex) {
System.err.println("impossible to parse to yyyy-MM-dd HH:mm");
}
try {
LocalDate localDate = LocalDate.parse(format, formatter);
return localDate.format(DateTimeFormatter.ofPattern(retFormat));
} catch (DateTimeParseException ex) {
System.err.println("impossible to parse to yyyy_dd_MM");
}
return null;
}
for old java versions
public String convertDateFormat(String format) {
DateFormat df1 = new SimpleDateFormat("YYYY_MM_DD");
DateFormat df2 = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
DateFormat dfResult = new SimpleDateFormat("DDMMMYYYY ");
Date d = null;
try {
d = df1.parse(format);
return dfResult.format(d);
} catch (ParseException e) {
System.err.println("impossible to parse to " + "YYYY_MM_DD");
}
try {
d = df2.parse(format);
return dfResult.format(d);
} catch (ParseException e) {
System.err.println("impossible to parse to " + "EEE MMM dd HH:mm:ss z yyyy");
}
return null;
}
if you give any other invalid string, the string returned will be null!
You can use this approach and declare optional section in pattern :
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("[yyyy_MM_dd][EEE MMM dd HH:mm:ss Z yyyy]", Locale.ENGLISH);
This formatter will parse date for both patterns and then you can easily convert it to required format.
P.S. I've tested it but not sure which date should be parsable for EEE MMM dd HH:mm:ss Z yyyy template. So just play with it and use Java 8 approaches (Java Time)

DateFormat: loses the locale settings after parsing

I see that I lose the locale specific setting while parsing a date with DateFormat..
DateFormat date1 = DateFormat.getDateInstance(DateFormat.LONG,Locale.ITALY);// Long
Date datE = date1.parse("13 settembre 2013", pp1);
System.err.println("datE is: "+datE);
This is the output not localized that I get: date 34 is: Fri Sep 13 00:00:00 CEST 2013
is there any way to make it persistent? (would be logical expecting an Italian formatted date)
The Date class has an internal date format.
public String toString() {
// "EEE MMM dd HH:mm:ss zzz yyyy";
BaseCalendar.Date date = normalize();
StringBuilder sb = new StringBuilder(28);
int index = date.getDayOfWeek();
if (index == gcal.SUNDAY) {
index = 8;
}
convertToAbbr(sb, wtb[index]).append(' '); // EEE
convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' '); // MMM
CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd
CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':'); // HH
CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
TimeZone zi = date.getZone();
if (zi != null) {
sb.append(zi.getDisplayName(date.isDaylightTime(), zi.SHORT, Locale.US)); // zzz
} else {
sb.append("GMT");
}
sb.append(' ').append(date.getYear()); // yyyy
return sb.toString();
}
Which DateFormat you parsed it with doesn't affect that.
The call
System.err.println("datE is: "+datE);
performs String concatenation which implicitly calls toString() on reference types, ie. datE.toString().
Dates don't have a Locale. They're just a wrapper around a long - milliseconds since epoch.

Android parse pubDate tag from RSS xml feed

I'm having problem parsing the tag from an RSS Feed.
The format is like this: Mon, 16 Apr 2012 16:42:30 +0000
I created a function parseDate which does the trick, but the fact is it parses the date using Locale.US, which returns the date but using the US locale, so it returns the time +2 hours. If I don't provide the Locale.US parameter, I get a ParseException.
How can I accomplish a correct parsing so the date provided is correct for any Local?
Here's the function:
public String parseDate (String dateraw){
String returndate;
try {String format = "EEE, dd MMM yyyy kk:mm:ss Z";
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy kk:mm:ss z",Locale.US);
Date formatedDate = sdf.parse(dateraw);
Calendar c= Calendar.getInstance();
c.setTime(formatedDate);
returndate=""+c.get(Calendar.DAY_OF_MONTH)+"/"+c.get(Calendar.MONTH)+"/"+c.get(Calendar.YEAR)+" "+c.get(Calendar.HOUR_OF_DAY)+":"+c.get(Calendar.MINUTE);
return returndate;
} catch (ParseException e) {
e.printStackTrace();
// TODO Auto-generated catch block
return "NO DATE AVAILABLE";
}
}
Your code works fine. The date is parsed and is not timezone dependent.
Try to print your current timezone or calendar timezone and see if that is correct:
//...
Calendar c = Calendar.getInstance();
c.setTime(formatedDate);
Log.i(TAG, c.getTimeZone().getID());
Log.i(TAG, TimeZone.getDefault().getID());
//...

Categories