DateFormat does not work? - java

String selectedDate = "2012-" + createdMonth + "-" + createdDay;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
createdDate = dateFormat.parse(selectedDate);
} catch (ParseException e1) {
e1.printStackTrace();
}
System.out.println(createdDate);
Basically when I print createdDate, it will display something like this :
Thu Mar 08 00:00:00 CST 2012
Instead of something of this format "yyyy-MM-dd". Thanks a bunch!

The parse method returns a java.util.Date and that is the what the Date implementation of toString() returns.

You need to print as below. Point is that you need to use the formatter object you have created while printing as well.
System.out.println(dateFormat.format(createdDate));

use dateFormat.format(createdDate)

You seem to think that createdDate, which is a Date object, has the format yyyy-MM-dd. It doesn't. Date objects don't have a format - they just contain a timestamp, just like numbers are just numbers, which don't have a format by themselves.
A SimpleDateFormat object is used to parse a String into a Date object, or format a Date object into a String.
If you have a Date object and you want to display the date in a particular format, then convert it to a String with the appropriate format using a SimpleDateFormat object:
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
String text = fmt.format(createdDate);
System.out.println("Created: " + text);
If you print a Date object without explicitly formatting it, it will be formatted using a default format, which is why you see Thu Mar 08 00:00:00 CST 2012.
A Date object does not somehow remember what the format was of the String that you parsed it from.

Related

Wrong output for date format in Grails

I'm trying to format a Date in Grails, here is my code in the controller:
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
empRefInstance.startDate=sdf.parse(params.startDate)
empRefInstance.endDate=sdf.parse(params.endDate)
println ("dates " + empRefInstance.startDate +" "+empRefInstance.endDate)
the output supposed to be 01-05-2016 as per the format i defined but the output of the both date in this format
Sun May 01 00:00:00 EEST 2016
is there something wrong in the formater?
There is nothing wrong with the formatter. You're not using one for the output. Something like this will give you the expected output:
println empRefInstance.startDate.format('dd-MM-yyyy')
You are not formatting the output instead you have only parsed.
Formatting: Converting the Date to String (the format method)
Parsing: Converting the String to Date (the parse method)
To format, you need to do like this:
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
// First you are converting the incoming date string to a date
empRefInstance.startDate = sdf.parse(params.startDate)
empRefInstance.endDate=sdf.parse(params.endDate)
// Now we have to conert the date object to string and print it
println ("dates " + sdf.format(empRefInstance.startDate) + " "+sdf.format(empRefInstance.endDate))
When you print a Date object in Groovy/Java, it's default implementation of toString() will be invoked hence you were getting output like Sun May 01 00:00:00 EEST 2016
Also, Groovy adds a format method in Date class to direct allow formatting. You can even use that as well.
println("dates " + empRefInstance.startDate.format("dd-MM-yyyy") + " " + empRefInstance.endDate.format("dd-MM-yyyy"))

Parse a string to date in specific format

I have a TimeStamp '2013-06-24 10:46:11.0' and I need to cut off the .0 part, so what I did was to use the SimpleDateFormat to parse it to String and back then parse it to date, the first conversion was fine but the second (string to date) throws a java date time.
public void convert(Object object) {
Date date;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = object().getDate();
String formated = format.format(date);
try {
date = format.parse(formated);
} catch (ParseException ex) {
Logger.getLogger(DlgConsultaFactura.class.getName()).log(Level.SEVERE, null, ex);
}
}
What I expect is a date like this 2013-06-24 10:46:11, but what I got is this date Mon Jun 24 10:46:11 CDT 2013
Any help will be appreciated. Thanks.
Mon Jun 24 10:46:11 CDT 2013 and 2013-06-24 10:46:11 is actually same value. Mon Jun 24 10:46:11 CDT 2013 is as per your default locale.
You're getting confused between date's internal representation and its display format.
To print in 2013-06-24 10:46:11 you can use same SimpleDateFormat object again.
You can use DateFormat#format(Date) to print the date or return the String representation in your desired format i.e. "yyyy-MM-dd HH:mm:ss". Something like this:
String myDt = format.format(date);
// 2013-06-24 10:46:11
Not the best way but a quick and easy one if you want just the string representation of the date ...
formated = formated.substring(0, formated.length()-2);
:)
DateFormat i.e. SimpleDateFormat just formats the date as per your need.
Parse returns the Date representation of the String (or timestamp in your case) passed in.
Format returns the String representation of the Date object passed in.
In both the cases , you see the same date just the representation is different.

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

change string to date as per the required date Format

I have to get a Date in type Date, not in String.
I have this code:
DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
Date date1 = new Date();
String date = (formatter.format(date1));
// At this point I get the date in correct format i.e 05/24/11
Date todaysDate = (Date)formatter.parse(date);
// But after this I get the date in format : Tue May 24 00:00:00 EDT 2011
// whereas I Want to get the date like above i.e 05/24/11
// And in type Date, not in type String
If anyone could help, thanks
The Date object just represents a point in time and has no notion of a format (or time zone). If you print out a Date object it first converts it to a String using the default formatting of EEE MMM dd HH:mm:ss zzz yyyy. If you want a specific formatting when you print it or otherwise represent it as a String, you'll need to use a formatter just like you already have.
In other words, you want Date.toString() to return the same as DateFormat.format()? You could just do exactly that:
public class MyDate extends Date {
DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
public String toString() {
return this.formatter.format(this);
}
}
But do you really want to mix up presentation (date format) with your data?
There is no problem here, you have a Date representing and can save it into the DB as it is now. If you print it to the console it gets formatted according the default rules, this is why you think it is different from what you need, but it has actually already the right value.
So just go ahead and put it into your DB.
Chances are that you DB will hold on getting a Timestamp, in this case you can create one:
Date d = ...
java.sql.Timestamp ts = new java.sql.Timestamp(d.getTime());
and save this one.

Parsing date from Calendar in Java

I am having following function
public static Date parseDate(String date, String format) throws ParseException
{
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.parse(date);
}
I am using this as follows in my code
Calendar eDate = Calendar.getInstance();
eDate.add(Calendar.DAY_OF_MONTH,10);
Date date = null;
try {
date = parseDate(eDate.getTime().toString(),"yyyy-MM-dd hh-mm-ss");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But it is throwing -
java.text.ParseException: Unparseable date
What is the problem here?
The format is not stored in the Date. It is stored in the String. The Date#toString() returns a fixed format which is described in its Javadoc.
Do the formatting only at the moment you need to display a Date to a human as a String.
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, 10);
Date date = calendar.getTime();
String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
System.out.println(formattedDate);
Note that MM stands for months and mm for minutes. See also SimpleDateFormat javadoc.
You'll be happy to hear that there's never a need to parse a date from a Calendar object: The way to pull a Date out of a Calendar is via the getTime() method.
EDIT:
To output the date in eDate in ISO style format:
final DateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
String formattedDate = isoFormat.format(eDate.getTime());
That's untested, but I think it should work.
You're currently formatting with the default format from java.util.Date, and then parsing with a potentially different format. You should also change your format string - it's currently using a 12 hour clock with no am/pm indicator, and minutes twice. I think you mean: "yyyy-MM-dd HH-mm-ss"
Don't use toString() for anything like that. toString() should be used only for debug messages.
Use DateFormat.format(..) to produce a string in a predictable form.
You're inserting a Zulu Timestamp (UNIX), getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 GMT. Then you define the format as yyyy-mm-dd hh-mm-ss and try to parse the timestamp with this pattern. Which doesn't match.
You could use Date date = calendar.getTime(); and then format it via new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(date);
you can simply use the date returned by the calendar, instead of transforming it into string and back into a date (apparently using a wrong date format). The date can be obtained by:
eDate.getTime()
There seems to be no need for SimpleDateFormat in your case.
Check the Date.toString() method.
The api states that it returns it in
the format:
dow mon dd hh:mm:ss zzz yyyy
which is:
Mon Jan 28 14:22:07 EST 2004
You are telling the parser to expect: 2004-01-28 14-22-07
eDate.getTime().toString()
returns a String representation of a date in this format:
dow mon dd hh:mm:ss zzz yyyy (see the java.util.Date API).
You are trying to parse a date using this format:
yyyy-mm-dd hh-mm-ss .
The code is correctly throwing the ParseException.

Categories

Resources