Java: How parse String to Date correct? - java

I try to parse a Date from a String:
String dateString = "Fr, 1. Jan";
DateFormat format = new SimpleDateFormat("EE, d. MMM");
Date date = null;
try {
date = format.parse(dateString);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(format.format(date));
And what I got as output is these:
Do, 1. Jan
Why did that happen and why isn't it the same output as the input?

You forgot the year. When you parse it, you will get in the year 1970 (the Friday will be ignored). When you parse back, you will parse the date 01 Jan 1970, which was a Thursday. This should work:
String dateString = "Fr, 1. Jan";
DateFormat format = new SimpleDateFormat("EE, d. MMM");
Date date = null;
try {
date = format.parse(dateString);
} catch (Exception e) {
e.printStackTrace();
}
date.setYear(new Date().getYear()); //alternativ: date.setYear(2016);
System.out.println(date);
System.out.println(format.format(date));

A Date in Java begins at 01-01-1970. The 1st January in 1970 was a Thursday, therefore it parses the day as Thursday instead of Friday. You would have to add a year in order to guarantee that it's a Friday.

"Do" is the first 2 letters of "Donnerstag", which is German for "Thursday". Judging by your last name "Baum" (German for "tree"), I'm guessing that is not a coincidence. Also, 1970-01-01 was a Thursday, and if you don't specify the year, you get start-of-epoch.
The date format "E" is the day-of-week as a word - the more "E"'s you specify, the more letters of that word get rendered; "EE" would render "Thursday" as "Do" in a German locale, which is suspect is your default locale.
Your code as-is explodes for me, but this similar code produces the same output you get:
String dateString = "Fri, 1. Jan";
DateFormat format = new SimpleDateFormat("EEE, d. MMM");
Date date = format.parse(dateString);
DateFormat format2 = new SimpleDateFormat("EE, d. MMM", Locale.GERMAN);
System.out.println(format2.format(date));
Output:
Do, 1. Jan

Related

SimpleDateFormat.parse() - generates wrong date for different date-formats

Below is my code to parse the date using SimpleDateFormat with pattern:
String pattern = "yyyy-MM-dd";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
Date date = format.parse("05-21-2030");
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
You can see the date which I passed to parse is different from date format which is specified in SimpleDateFormat. In this case I was expecting kind of excpetion as format is different but it parsed successfully with some different date values. I got the output - Tue Mar 22 00:00:00 IST 12
When I pass the same format like 2030-05-21 it works fine.
Can you guys please let me know how can I prevent such things in my code?
Basically you want SimpleDateFormat to be strict, so set lenient to false.
SimpleDateFormat format = new SimpleDateFormat(pattern);
format.setLenient(false);
If you can afford using Java 8 time API, its formatter works as expected:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
try {
LocalDate date = LocalDate.parse("2030-05-21", formatter);
System.out.println(date);
LocalDate date2 = LocalDate.parse("05-21-2030", formatter);
System.out.println(date2);
} catch (DateTimeParseException e) {
e.printStackTrace();
}
Output:
2030-05-21
java.time.format.DateTimeParseException: Text '05-21-2030' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1947)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1849)
at java.time.LocalDate.parse(LocalDate.java:400)
at java8.Snippet.main(Snippet.java:25)

Format timestamp from database to Java

I have this weird format of date and time on my Oracle SQL Developer :
2015-4-14.1.39. 33. 870000000
I tried to format the given date to MM-dd-yyyy HH:mm:ss, but it gives me exception:
java.text.ParseException: Unparseable date: "2015-4-14.1.39. 33. 870000000"
The following is the code:
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
try {
String ts = "2015-4-14.1.39. 33. 870000000";
Date date = formatter.parse(ts);
String S = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(date);
System.out.println(S);
} catch (Exception e) {
e.printStackTrace();
}
The problem is that the given date string does not match the specified format. Try use the following format:
SimpleDateFormat df = new SimpleDateFormat("yyyy-M-dd.H.m. s. S");
String ts = "2015-4-14.1.39. 33. 870000000";
df.parse(ts);
Where
yyyy for year
M for month in year
dd for day in month
H for hour in date (0-23)
m for minute in hour
s for second in minute
S for millisecond

Convert string to DateFormat

i am trying to convert a string utc date to Date. by using the following code
This is My UTC String Date - 12/31/2013 8:40:00 AM
i want to convert this string to UTC Date.
static final String DATEFORMAT = "dd/MM/yyyy HH:mm:ss aa";
StringDateToDate("**12/31/2013 8:40:00 AM**");
public static Date StringDateToDate(String StrDate)
{
Date dateToReturn = null;
SimpleDateFormat dateFormat = new SimpleDateFormat(DATEFORMAT);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
dateToReturn = dateFormat.parse(StrDate);
} catch (ParseException e) {
e.printStackTrace();
}
return dateToReturn;
}
but i am getting the wrong date in wrong format (sun jul 12 19:40:00 CDT 2015). how can i convert this utc date string to utc date. i am getting the utcdatestring from a rest webservice in XML format.
Just try this. Probably the order of your Date Format is wrong
String dtStart = "12/31/2013 8:40:00 AM";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss aa");
Date date = format.parse(dtStart);
System.out.println(date);
First your date format is wrong it should be :
static final String DATEFORMAT = "MM/dd/yyyy HH:mm:ss aa";
secondly, your input has to not have the asterixs(*) like this :
Date a = StringDateToDate("12/31/2013 8:40:00 AM");
//yea I know I should be using Log but I'm testing on java
System.out.println(a.toString());
If you really want the asterixs, do this :
String b = "**12/31/2013 8:40:00 AM**";
StringDateToDate(b.substring(2, b.length()-2));
Your input is wrong(there is no 31 month) , change it to a valid month
StringDateToDate("12/01/2013 8:40:00 AM");
to be compatible with the DateFormat
or Change your Dateformat to suit your input value
static final String DATEFORMAT = "MM/dd/yyyy HH:mm:ss aa";
Change your dateformat like this.
String DATEFORMAT = "MM/dd/yyyy HH:mm:ss aa";
G Era designator Text AD
y Year Year 1996; 96
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 in week Text Tuesday; Tue
u Day number of week 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
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00
This is the Date and Time Patterns.
String string = "January 2, 2010";
Date date = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(string);
System.out.println(date);
Your date format should be this in order to parse the String you have given here.
static final String DATEFORMAT = "MM/dd/yyyy HH:mm:ss aa";
And also watch out for HH. HH is Hour in day (0-23). If your input date hour is 0-11 (possibly like this since AM\PM is given and patter has aa at the end) then KK must be used instead of HH.
The result obtained is not wrong but it is what expected.
By default, parsing is lenient. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format.
The heuristics uses the number specified for month not as months in the specified year but as months since the specified year, 31 months are 2 years and 7 months so: 01/2013 + 2years + 7 months = 07/2015.
This can be confusing so the suggestion is to set the lenient parsing to false before parsing but when pattern doesn't match something in your string a parsing exception is thrown.
public static Date StringDateToDate(String StrDate) {
Date dateToReturn = null;
SimpleDateFormat dateFormat = new SimpleDateFormat(DATEFORMAT);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
dateFormat.setLenient(false);
try {
dateToReturn = dateFormat.parse(StrDate);
} catch (ParseException e) {
e.printStackTrace();
}
return dateToReturn;
}

Using SimpleDateFormat in java

I am trying the following code,
Calendar signupDate = Calendar.getInstance();
signupDate.set(Calendar.YEAR, 2014);
signupDate.set(Calendar.MONTH, 01);
signupDate.set(Calendar.DAY_OF_MONTH, 01);
Date signupDateTime = signupDate.getTime();
new Object[]{signupDateTime};
Date date = (Date) params[0];
String format = (String) params[1];
try {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.ENGLISH);
String expDateStr = (String) sdf.format(date);
System.out.println("Expiration Date: "+expDateStr);
} catch (Throwable t) {
throw new RuntimeException("Could not execute DateToString function for Date:" + params[0] + " with Pattern:" + params[1], t);
}
This program prints: Expiration Date: 2014-02-32
While debugging, i reached in into java.text.DateFormat class in Java API into the following function,
public final String format(Date date)
{
return format(date, new StringBuffer(),
DontCareFieldPosition.INSTANCE).toString();
}
Runtime value of date parameter for format function is: Fri Feb 01 17:58:30 PST 2013
But this function returns: 2014-02-32
I am not sure how does formatting converts 01 to 32.
Any suggestion?
Thanks,
Vijay Bhore
Feb 1st is the 32nd day of the year. Your SimpleDateFormat is probably using DD instead of dd.
This is dangerous:
signupDate.set(Calendar.MONTH, 01);
Don't use magic numbers like this since you or the next coder to maintain this code might not know that months are 0 based, that this sets the month to February not January.
Better:
signupDate.set(Calendar.MONTH, Calendar.JANUARY);
or
signupDate.set(Calendar.MONTH, Calendar.FEBRUARY);
Whichever was desired.

Fast way to parse a Long date into Month-Day-Year String

How do you parse a Long date like: 1366222239935 into a String of space-separated Month-Day-Year? Like into "Apr 18 2013"
Passing it on a java.util.Date and to a String will give a String of date which contains so many info that I don't need for rendering in my GWT application.
Need to do this style since I will be passing the result into 3 <span> elements; so actually the space-separated date will be split into parts:
Month
Day
Year
As gwt won't support SimpleDateFormat
instead use Gwt DateTimeFormat
DateTimeFormat f = DateTimeFormat.getFormat("dd-MMM-yyyy");
String datestring =f.format(dateGeneratedbyLong);
And make sure the DateTimeFormat import also which you can use both client and server side .
There is another class with same name but package is different which is client(restricts you to use on client side only )
try to use SimpleDataFormat check http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html>
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yy");
String dateAsString = simpleDateFormat.format(new Date());
You could convert it to a Date and then manually build your String like this.-
Date date = new Date(timeInMils);
String res = date.get(Calendar.MONTH) + " " +
date.get(Calendar.DAY_OF_MONTH) + " " +
date.get(Calendar.YEAR);
That Long number is simply the number of milliseconds since the JavaScript epoch (1/1/1970 at midnight, UTC time). So, instead of parsing it, use the constructor for the Date object:
var myDate = new Date(1366222239935);
alert(myDate);
That will show "Wed Apr 17 2013 11:10:39 GMT-0700 (Pacific Daylight Time)". I am in PST, but it will default to whatever timezone you have in your locale settings.
Inside a GWT app in Java, simply do:
Date date=new Date(1366222239935);
Then you can use SimpleDateFormat to render it as "dd/MM/yy".
See http://www.w3schools.com/jsref/jsref_obj_date.asp
Do like this
Date d = new Date();
d.setTime(1366222239935l);
System.out.println(d);
SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd yyyy");
try {
System.out.println(sdf.format((d)));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long diff = 1366222239935l;
Date date = new Date(diff);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
System.out.println(sdf.format(date));

Categories

Resources