How can I get the current date of the system with this format yyyy-MM-dd
I want this
SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String strDate = formatDate.format(now);
return strDate;
but returning a Date instead of a String.
Any help is greatly appreciated.
UPDATE: If that's the case, can I parse my String to Date?
How can i get the current date of the system with this format yyyy-MM-dd but returns Date instead of String.
You can't. There's no such thing as "a Date with a format" any more than there's the concept of "an int with a format". A Date value is just a point in time, with no associated text format, calendar system or time zone.
Using new Date() will get you a Date object representing the current instant in time, and nothing else. How you use that is up to you - but if you return it from a method then there is no associated date (as the date will vary by time zone), no format etc - it's up to the calling code to use it appropriately.
You might want to consider using Joda Time which at least has a LocalDate type - although you still need to consider which time zone you want to use when you think about "the current date". (And there's still no formatting information associated with the value.)
EDIT: To answer your update, you can just use SimpleDateFormat to parse - but it's not clear where your string has come from to start with. This sounds like the opposite requirement from the rest of your question.
since you cant change Date format build your own CustomDate, it is just a representation of time.
on the method which recieves the date as a string
use another simpledateformatter
and convert the string into date by using
simpledateformatter.parse(strDate);
You can use this .!!
String formatDate = new SimpleDateFormat("yyyy-MM-dd").format( yourDate);
Related
I'm reading information from a file (.csv) that will be inserted to a database after validation and approval from the end user. The text file is read, validated and its information loaded to a List containing forms which are used to check if the data already exist in database.
The problem arises when parsing the String to Date. The SimpleDateFormat.parse() method returns an unexpected date format even when the pattern for SimpleDateFormat is "yyyy-MM-dd".
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
Parsing the loaded values to the travel object:
travel.setDate( dateFormat.parse( form.getTravelDate() ));
In debugger the form shows the date as:
"2012-12-12"
It is read as intended. However when parsed becomes:
Wed Dec 12 00:00:00 CST 2012
I've spent the whole day trying to solve this but I'm out of ideas at this point. Afaik the pattern is alright and I've tried adding a locale to no avail.
Edit: the problem is when I need to insert the values to the database using Hibernate. The not desired format also ends up showing in the Database.
The data is show in a .jsp page using
HttpServletRequest("table",travelList);
The date format I don't need shows here, when in the past this issue never happened. At last the information is sent to the database where the problem persists.
No, it "becomes" a java.util.Date value. If you're then converting it back to a string by calling Date.toString(), you should consult the Date.toString() documentation for what to expect.
The value stored in the Date is just a point in time - the number of milliseconds since the Unix epoch. There's no format in there, no time zone etc. It also doesn't know that it was only a date value rather than a date and time (the naming of Date is one of the many unfortunate aspects of the API).
It's crucial that you mentally separate "the result of the parse operation" from "the string value that is used to represent that result if I call toString"".
I'd also advise you to set the time zone on your SimpleDateFormat to UTC when parsing a date - that way you know that you can't possibly have any ambiguous or skipped times leading to hard-to-predict behaviour. (Of course, you then need to know that you'll have parsed the date to "the start of the UTC date" and handle it appropriately elsewhere.)
You need to use the formatter when printing the Date as well.
dateFormat.format( travel.getDate() );
When your parse the String using a DateFormat, you get a complete Date object with the time units missing in the string initialized to zero. In your example, that's hours, minutes and seconds.
By default, if you do not use a formatter, Date's default string representation (provided by its toString() method) gets printed.
Parsing doesn't mean it format, it simply parse it as text to a java.util.Date object. See parse method in documentation.
You need to use the format method.
dateFormat.format(travel.getDate())
See documentation for more details.
if form.getTravelDate() is returning String then First Parse the Date from String
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
Date parsedDate=dateFormat.parse(form.getTravelDate());
// Here parsedDate is in form Wed Dec 12 00:00:00 CST 2012
Now Format the Date using the Same SImpleDateFormat to get the desired output
System.out.println(dateFormat.format(parsedDate));
Your Desired Output
2012-12-12
Update
Assuming data Type of Columns in which we insert this data in Database is of Date Type not varchar then use the below statement
travel.setDate(dateFormat.format(parsedDate));
As I understand parse method returns Date. Below is the parse method syntax.
public Date parse(String source)
throws ParseException
So, you need to parse the string date and store into a Date variable. Then format the Date variable using SimpleDateFormat.
//getTravelDate is "2012-12-12"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
Date dtObj=new Date();
dtObj=dateFormat.parse(form.getTravelDate()); //Store in date variable
System.out.println(dateFormat.format(dtObj)); // Now format the date object
The final output will be 2012-12-12. Hope it will help you.
How to get the pattern of the given date object
I am getting one Date object as a parameter in my method and I want to know the pattern of the date to convert it into user selected timezone.
You've misunderstood what a Date means. It's just a number of milliseconds since the Unix epoch. It has no concept of time zone, calendar or text format. If it helps, think of it as being a bit like int - an int isn't in hex, decimal or binary - it's just a number within a certain range. If you parse "1a" as hex, that gives an indistinguishable result from parsing "26" as decimal. The same goes for Date.
Of course, this was already explained in comments to some extent, but your reply of:
ok, but while i getting the date object which already set a format i want to know that format.
... suggests you didn't really understood it. The concept of "which already set a format" makes no sense in the context of a Date.
If you need a particular format to be applied, you should pass the DateFormat along as well as the Date.
You can't from the date object itself however (depending on your exact requirements) you could use
DateFormat.getDateTimeInstance()
Which will return to you the default style and format for the locale however like I said that's dependant on your requirement...
The alternative is change your method signature to accept the format as well.
You should create DateFormat. Date knows nothing about TimeZone.
Date date = new Date();
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
// Set TimeZone
formatter.setTimeZone(TimeZone.getTimeZone("EST"));
System.out.println(formatter.format(date));
// Change timezone
formatter.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println(formatter.format(date));
I am trying to format a calendar string to indicate a time zone offset other than my local one. I am aware I could create a simple formatting string and use the Calendar.get(int) method to fill in all the values, but this does not feel like the right way to do this.
Java has a DateFormat, specifically I am trying to use the SimpleDateFormat. The problem is that the format() method of these classes expects a Date object.
I am primarily working with Calendar objects since I believe those are the recommended structure in Java. So, when I go to format my result time, I call Calendar.getTime() which returns a Date object which can be passed into the SimpleDateFormat object.
Until now, I thought this was perfectly simple, but here is where the problem comes in.
Whenever one calls the Calendar.getTime() method, the Date returned is always in the local time zone, regardless of the time zone of the Calendar.
So, I always get the time printed in the local time zone when I pass it to my SimpleDateFormat, which is not what I want. All the research I have done so far says it can't be done and all the examples I have seen simply use the Calendar.get(int) method to fill in some blanks. This seems terrible, why have a DateFormat class if it is going to be so useless?
Here is some example code so you can see what I mean, paste this into your favourite test class:
private static final SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
public static void main(String[] args)
{
try
{
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST"));
cal.setTimeInMillis(parser.parse("2012-10-09T22:01:49.108-0700").getTime());
System.out.println(formatter.format(cal.getTime()));
}
catch(ParseException e)
{
e.printStackTrace();
}
}
Output produced (because I am running in Central Time Zone): 2012-10-10T00:01:49-0500
Output expected (should not matter what time zone it is run from): 2012-10-10T01:01:49-0400
To summarize question: Is there a way to make the DateFormat in java accept a Calendar, or a way to get a Date that is not in the local timezone, or is there another class I should be using altogether for this formatting?
Whenever one calls the Calendar.getTime() method, the Date returned is always in the local time zone, regardless of the time zone of the Calendar.
No, it's not. Date doesn't have a time zone. It's just the number of milliseconds since the Unix epoch. Its toString() method does convert it to the local time zone, but that's not part of the information in the Date object.
All you need to do is set the time zone of the formatter to be the same as the time zone of the calendar.
formatter.setTimeZone(calendar.getTimeZone());
... or just set the calendar to be used entirely:
formatter.setCalendar(calendar);
(It's not immediately clear to me whether the latter approach will mean that the calendar can lose its value... basically the Java classes mix "calendar system", "time zone" and "value within the calendar" in a single type, which is very unfortunate.)
I agree with Ian though, in terms of Joda Time being a far more pleasant API to use.
I would give up on the built in java date and time classes for this and use joda time instead. It is designed to handle ISO8601 format strings properly and does the right thing with timezones.
Date is not having any TimeZone, its just the number of milliseconds since Epoch time, represented in a human readable format. We can use "DateFormat" class.
TimeZone tz = TimeZone.getTimeZone("America/Buenos_Aires");
Calendar cal = Calendar.getInstance(tz);
Date d = cal.getTime();
DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm aaa");
df.setTimeZone(tz);
String s = df.format(cal.getTime());
System.out.println(s);
Good day Lovely people
Please help a brother out. Well I'm a master in visual basic but in java let me rather not say.
In VB here are my methods:
System.DateTime.Now.ToLongTimeString()
System.DateTime.Now.ToString() + "/" + System.DateTime.Now.Month.ToString() + "/" + System.DateTime.Now.Year.ToString()
The first method will return the exact time e.g = 12:08:36 AM
And the second method will return the exact date e.g = 2012/09/26
I want to get the very same results but using java.How do i go about doing that.
Oooh Thanks in advance.
In .NET, DateTime.Now gives you the local date and time, in your local time zone.
If you use new Date() or the like in Java, it will give you a value which has no awareness of time zones. To take time zones into account, you should either create a Calendar which has the right time zone, or if you want to create an appropriate string you should use SimpleDateFormat - again, set to the right time zone before formatting. For example:
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd", Locale.US);
format.setTimeZone(...); // Whichever time zone you want
String text = format.format(new Date()); // "now"
Also note that Joda Time is a much better Java API for date/time than the built-in Calendar and Date classes.
Finally, your second piece of sample code in .NET is buggy - you should only evaluate DateTime.Now once; ideally just passing in a format string e.g. DateTime.Now.ToString("yyyy/MM/dd"). Even if you want to convert each bit to a string separately, however, you fetch the value once to a local variable and then reuse it. Otherwise, if you execute that code around midnight, the date can change - so for example, if you executed it just before the start of 2013, you could end up with a string of "2012/12/1" or "2012/1/1" neither of which would be correct.
Use java.text.SimpleDateFormat class to format date and new java.util.Date() will create an instance system date default.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
SimpleDateFormat dateFormat1 = new SimpleDateFormat("hh:mm:ss a");
System.out.println(dateFormat.format(new Date)); //2012/09/26
System.out.println(dateFormat1.format(new Date)); //12:08:36 AM
To get the object representing the current date, you can use just new Date(), to format it, use SimpleDateFormat.
I am trying to import a given string representing a Date in the format:
2007-03-12T00:00:00.000+01:00
Now to create a new Date Object i use Joda Library using:
DateTime date = new DateTime(year, month, day, hour, minute, second);
However, i want to make sure two things here:
How to handle GTM +1 in this date time context?
Is there anyway,
that i don't have to parse this string, and the Date Object can be
initialized directly with this string?
DateTime date = DateTime.parse("2007-03-12T00:00:00.000+01:00");
As has been mentioned in other answers, the offset is supposed to be parsed along with the rest of the string according to the documentation.
You can parse that date string using SimpleDateFormat, then pass that Date into a Joda class:
String dateStr = "2007-03-12T00:00:00.000+01:00";
SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date date = sdf.parse( dateStr.replaceAll(":(?=..$)", "")); // remove last colon
Note that you must remove the last colon so the offset is a RFC 822 time zone like +0100, which I did using String.replaceAll()
Both your questions can be answered by reading the documentation for the class
timezone is handled by the class. Look for the constructor which takes the timezone argument.
Yes you can create the DateTime object using the string. DateTime.parse(String) is available to do that. There is also another method available to parse custom date formats if required.