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.
Related
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.
While looking at this question, I discovered that both the OP's and the accepted answer's code, when run, produce a ParseException. Here is the code:
String dateString = new java.util.Date().toString();
System.out.println(dateString);
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date date = format.parse(dateString);
System.out.println(date.toString());
After closely examining how the date string printed differs with the format provided, I still can't find why they don't match. Here is the date string printed:
Sat Aug 19 18:58:41 BST 2017
My instincts tell me that the reason why this does not work is that my locale is different - Locale.getDefualt() returns ja_JP.
The pattern does not matter, but the locale does.
Date#toString uses Locale.US and English names for days, months and time zones, while SimpleDateFormat(String) uses your default locale (specifically: Locale.getDefault(Locale.Category.FORMAT)). If those two locales do not match, parsing may fail as the local names are not guaranteed to match.
So you should be fine with
new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
Excerpts from JDK 8:
SimpleDateFormat:
public SimpleDateFormat(String pattern)
{
this(pattern, Locale.getDefault(Locale.Category.FORMAT));
}
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();
}
[...]
private final static String wtb[] = {
"am", "pm",
"monday", "tuesday", "wednesday", "thursday", "friday",
"saturday", "sunday",
"january", "february", "march", "april", "may", "june",
"july", "august", "september", "october", "november", "december",
"gmt", "ut", "utc", "est", "edt", "cst", "cdt",
"mst", "mdt", "pst", "pdt"
what format can parse this dateString to a Date?
String dateString = "Oct 1, 2015 12:00:00 AM";
try {
SimpleDateFormat sdf = new SimpleDateFormat("");
sdf.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
The SimpleDateFormat Javadoc includes a table that says (in part)
Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996; 96
Y Week year Year 2009; 09
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day name in week Text Tuesday; Tue
u Day number of week (1 = Monday, ..., 7 = Sunday) Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
I think you want a format like MMM dd, yyyy hh:mm:ss a. Something like,
String userDateFormat = "MMM dd, yyyy hh:mm:ss a";
String dateString = "Oct 1, 2015 12:00:00 AM";
DateFormat sdf = new SimpleDateFormat(userDateFormat);
try {
Date date = sdf.parse(dateString);
System.out.println(sdf.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
Which outputs
Oct 01, 2015 12:00:00 AM
The Android reference for SimpleDateFormat has a table that can be used to build the format.
try {
SimpleDateFormat sdf = new SimpleDateFormat("MMM,dd, yyyy hh:mm:s a");
sdf.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
This will work.
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
sdf.parse(dateString);
you can use this if you want month as oct, jan etc
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
or for month digits you can use
SimpleDateFormat sdf = new SimpleDateFormat("MM dd, yyyy hh:mm:ss a");
try this date format to convert datestring
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
Formatting and parsing the various date formats we expect to encounter.
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import android.util.Log;
/**
* Utility class for formatting and parsing the various date formats we expect
* to encounter.
*/
public class DateUtils{
private static final String TAG = "DateUtils";
private static final SimpleDateFormat[] dateFormats;
private static final int dateFormat_default = 7;
private DateUtils() { }
static
{
final String[] possibleDateFormats =
{
"EEE, dd MMM yyyy HH:mm:ss z", // RFC_822
"EEE, dd MMM yyyy HH:mm zzzz",
"yyyy-MM-dd'T'HH:mm:ssZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSzzzz", // Blogger Atom feed has millisecs also
"yyyy-MM-dd'T'HH:mm:sszzzz",
"yyyy-MM-dd'T'HH:mm:ss z",
"yyyy-MM-dd'T'HH:mm:ssz", // ISO_8601
"yyyy-MM-dd'T'HH:mm:ss",
"yyyy-MM-dd'T'HHmmss.SSSz",
"yyyy-MM-dd"
};
dateFormats = new SimpleDateFormat[possibleDateFormats.length];
TimeZone gmtTZ = TimeZone.getTimeZone("GMT");
for (int i = 0; i < possibleDateFormats.length; i++)
{
/* TODO: Support other locales? */
dateFormats[i] = new SimpleDateFormat(possibleDateFormats[i],
Locale.ENGLISH);
dateFormats[i].setTimeZone(gmtTZ);
}
}
/**
* Parse a date string. The format of RSS/Atom dates come in many
* different forms, so this method is extremely flexible and attempts to
* understand many different formats.
*
* Copied verbatim from Informa 0.7.0-alpha2, ParserUtils.java.
*
* #param strdate
* Date string to attempt to parse.
*
* #return
* If successful, returns a {#link Date} object representing the parsed
* date; otherwise, null.
*/
public static Date parseDate(String strdate)
{
Date result = null;
strdate = strdate.trim();
if (strdate.length() > 10) {
// TODO deal with +4:00 (no zero before hour)
if ((strdate.substring(strdate.length() - 5).indexOf("+") == 0 || strdate
.substring(strdate.length() - 5).indexOf("-") == 0)
&& strdate.substring(strdate.length() - 5).indexOf(":") == 2) {
String sign = strdate.substring(strdate.length() - 5,
strdate.length() - 4);
strdate = strdate.substring(0, strdate.length() - 5) + sign + "0"
+ strdate.substring(strdate.length() - 4);
// logger.debug("CASE1 : new date " + strdate + " ? "
// + strdate.substring(0, strdate.length() - 5));
}
String dateEnd = strdate.substring(strdate.length() - 6);
// try to deal with -05:00 or +02:00 at end of date
// replace with -0500 or +0200
if ((dateEnd.indexOf("-") == 0 || dateEnd.indexOf("+") == 0)
&& dateEnd.indexOf(":") == 3) {
// TODO deal with GMT-00:03
if ("GMT".equals(strdate.substring(strdate.length() - 9, strdate
.length() - 6))) {
Log.d(TAG, "General time zone with offset, no change");
} else {
// continue treatment
String oldDate = strdate;
String newEnd = dateEnd.substring(0, 3) + dateEnd.substring(4);
strdate = oldDate.substring(0, oldDate.length() - 6) + newEnd;
// logger.debug("!!modifying string ->"+strdate);
}
}
}
int i = 0;
while (i < dateFormats.length) {
try {
result = dateFormats[i].parse(strdate);
// logger.debug("******Parsing Success "+strdate+"->"+result+" with
// "+dateFormats[i].toPattern());
break;
} catch (java.text.ParseException eA) {
i++;
}
}
return result;
}
/**
* Format a date in a manner that would be most suitable for serialized
* storage.
*
* #param date
* {#link Date} object to format.
*
* #return
* Robust, formatted date string.
*/
public static String formatDate(Date date)
{
return dateFormats[dateFormat_default].format(date);
}
}
Or you can use below function for Parse Date..
public static Date parseDate(String date, String format) throws ParseException {
if (date == null || date.length() == 0) {
return null;
}
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
return dateFormat.parse(date);
}
Hope it will help you.
Date and Time Pattern Result
"yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy" Wed, Jul 4, '01
"h:mm a" 12:08 PM
"hh 'o''clock' a, zzzz" 12 o'clock PM,Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z" Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" 2001-07-04T12:08:56.235-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX" 2001-07-04T12:08:56.235-07:00
"YYYY-'W'ww-u" 2001-W27-3
Then you can convert your date string like the follow,
String dateString="Oct 1, 2015 12:00:00 AM";
try {
SimpleDateFormat sdf = new SimpleDateFormat("MMM,dd, yyyy hh:mm:s a");
sdf.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
I am trying to parse the date in a particular custom format.
WEDNESDAY 25th JAN 2012 - 12:44:07 PM
like this..
I created a SimpleDateFormat for this..
SimpleDateFormat sdf = new SimpleDateFormat("EEEE DD MMM YYYY - HH:MM:SS aa" );
the problem is the literal for the days. it is coming like 25th, 23rd, 02nd.I am getting exception for this thing...
help how to overcome this problem.
You can remove the literal for the day using a regex like this.
String dateString = "WEDNESDAY 25th JAN 2012 - 12:44:07 PM";
SimpleDateFormat format = new SimpleDateFormat("EEEEEEE dd MMM yyyy - HH:mm:ss aa", new Locale("EN"));
dateString = dateString.replaceAll("(.*[0-9]{1,2})(st|nd|rd|th)(.*)", "$1$3");
Date parsedDate = format.parse(dateString);
System.out.println(parsedDate);
(Ignore the Locale, i'm from somewhere else :) )
You could split the date string you're trying to parse into parts and remove the offending two letters in the following way:
String text = "WEDNESDAY 21st JAN 2012 - 12:44:07 PM";
String[] parts = text.split(" ", 3); // we only need 3 parts. No need splitting more
parts[1] = parts[1].substring(0, 2);
String parseableText = String.format("%s %s %s", parts[0], parts[1], parts[2]);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE dd MMM yyyy - hh:mm:ss aa" );
try {
java.util.Date dt = sdf.parse(parseableText);
} catch (ParseException e) {
e.printStackTrace();
}
Your parse string had some errors in it as well. Case is important for the date and time ptterns. See the SimpleDateFormat javadoc for a reference.
You are going to have to manually do it somehow.
e.g. A method as follows:
public static String makeItParseable(String dateStr) {
if(dateStr.contains("st ")) {
return dateStr.replace("st ", " ");
} else if(dateStr.contains("nd ")) {
return dateStr.replace("nd ", " ");
} else if(dateStr.contains("rd ")) {
return dateStr.replace("rd ", " ");
} else {
return dateStr.replace("th ", " ");
}
}
And use it make the input string parseable:
String dateStr = "WEDNESDAY 1st JAN 2012 - 12:44:07 PM";
dateStr = makeItParseable(dateStr);
DateFormat dateFormat = new SimpleDateFormat("EEEE dd MMM yyyy - hh:mm:ss a");
Date date = dateFormat.parse(dateStr);
Add ".th" to the format string, following what people stated in this thread
How do you format the day of the month to say "11th", "21st" or "23rd" in Java? (ordinal indicator)
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.