can we get the pattern of the given date object - java

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

Related

Formatting date in Java using SimpleDateFormat

I am trying to parse a date into an appropriate format, but I keep getting the error
Unparseable date
Can anyone tell me what the mistake is?
try {
System.out.println(new SimpleDateFormat("d-MMM-Y").parse("05-03-2018").toString());
} catch (ParseException e) {
e.printStackTrace();
}
I want the date to have this format:
05-Mar-18
Since you want to change the format, first read and parse the date (from String) of your own format in a Date type object. Then use that date object by formatting it into a new (desired) format using a SimpleDateFormat.
The error in your code is with the MMM and Y. MMM is the month in string while your input is a numeric value. Plus the Y in your SimpleDateFormat is an invalid year. yy is what needs to be added.
So here is a code that would fix your problem.
SimpleDateFormat dateFormat = new SimpleDateFormat("d-MM-yyyy");
Date date = dateFormat.parse("05-03-2018");
dateFormat = new SimpleDateFormat("dd-MMM-yy");
System.out.println(dateFormat.format(date));
I hope this is what you're looking for.
There are some concepts about dates you should be aware of.
There's a difference between a date and a text that represents a date.
Example: today's date is March 9th 2018. That date is just a concept, an idea of "a specific point in our calendar system".
The same date, though, can be represented in many formats. It can be "graphical", in the form of a circle around a number in a piece of paper with lots of other numbers in some specific order, or it can be in plain text, such as:
09/03/2018 (day/month/year)
03/09/2018 (monty/day/year)
2018-03-09 (ISO8601 format)
March, 9th 2018
9 de março de 2018 (in Portuguese)
2018年3月5日 (in Japanese)
and so on...
Note that the text representations are different, but all of them represent the same date (the same value).
With that in mind, let's see how Java works with these concepts.
a text is represented by a String. This class contains a sequence of characters, nothing more. These characters can represent anything; in this case, it's a date
a date was initially represented by java.util.Date, and then by java.util.Calendar, but those classes are full of problems and you should avoid them if possible. Today we have a better API for that.
With the java.time API (or the respective backport for versions lower than 8), you have easier and more reliable tools to deal with dates.
In your case, you have a String (a text representing a date) and you want to convert it to another format. You must do it in 2 steps:
convert the String to some date-type (transform the text to numerical day/month/year values) - that's called parsing
convert this date-type value to some format (transform the numerical values to text in a specific format) - that's called formatting
For step 1, you can use a LocalDate, a type that represents a date (day, month and year, without hours and without timezone), because that's what your input is:
String input = "05-03-2018";
DateTimeFormatter inputParser = DateTimeFormatter.ofPattern("dd-MM-yyyy");
// parse the input
LocalDate date = LocalDate.parse(input, inputParser);
That's more reliable than SimpleDateFormat because it solves lots of strange bugs and problems of the old API.
Now that we have our LocalDate object, we can do step 2:
// convert to another format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yy", Locale.ENGLISH);
String output = date.format(formatter);
Note that I used a java.util.Locale. That's because the output you want has a month name in English, and if you don't specify a locale, it'll use the JVM's default (and who guarantees it'll always be English? it's better to tell the API which language you're using instead of relying on the default configs, because those can be changed anytime, even by other applications running in the same JVM).
And how do I know which letters must be used in DateTimeFormatter? Well, I've just read the javadoc. Many developers ignore the documentation, but we must create the habit to check it, specially the javadoc, that tells you things like the difference between uppercase Y and lowercase y in SimpleDateFormat.

Joda time getting right time from dateTime

I have this simple code:
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm yyyy-MM-dd");
DateTime dateTime = formatter.withZone(DateTimeZone.forID("America/New_York")).parseDateTime("08:30 2015-06-01");
DateTime dateTime2 = formatter.withZone(DateTimeZone.forID("America/New_York")).parseDateTime("08:30 2015-12-01");
these are leap times. when I hit toString method, I got something like this:
2015-06-01T08:30:00.000-04:00
2015-12-01T08:30:00.000-05:00
which is correct, we can see UTC time - offset. But when I call getHourOfDay, I got 8 and not 4/3 as expected. What am I doing wrong? Please, share some advices here.
Well, from the Javadoc for DateTimeFormatter#withZone():
Returns a new formatter that will use the specified zone in preference to the zone of the printed object, or default zone on a parse.
So, you told the formatter to use the specific timezone on parsing AND output, and the input you gave it did NOT contain a timezone, so this is the expected result. In essence you said:
Here's a date string without timezone, parse it assuming America/New_York
Convert the date back to String, in the timezone America/New_York
This is what it did.

Java - SimpleDateFormat unexpected parsing behaviour

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 getDate with yyyy-MM-dd format

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

Java Date format

I have a spring web application that runs in Tomcat. I must set the date and number format for my application to a special format.
Can I set the format in any descriptor to the special in my application or I can set the all system format only?
I want to use this pattern: yyyy.mm.dd.
This code is wrong because it's not a standard locale pattern:
String currentDate = SimpleDateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.UK).format(new Date());
But I don't want type the pattern everywhere in the application, I want set the pattern once.
I want if I type this code:
String currentDate = SimpleDateFormat.getDateInstance(DateFormat.SHORT).format(new Date());
The result is: 2010.08.04.
Is it possible?
java.util.Date objects do not have a format by themselves (they only represent the date and time value, just like integers only represent a number value and don't know anything about formatting numbers).
There is no system-wide default date format setting. When you print a Date object by (implicitly or explicitly) calling toString() on it, it will be printed with a fixed, default format that you can't change:
System.out.println(new Date());
// Example output: Wed Aug 04 09:46:57 CEST 2010
If you want to show a date with a specific format, use a java.text.DateFormat object to format it. For example:
DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
System.out.println(df.format(new Date()));
// Example output: 04-08-2010 09:48:47
You can absolutely format a date any way you want, no matter if you use Spring or not. First though make sure that you really need a "special formatting", not just a format that is default for a certain locale (like deCH or svSE or enGB) because if you just want to convert a date to your countries native date formatting you can simply use
String currentDate = SimpleDateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.UK).format(new Date());
And if you really want a custom formatting, you can do like this
String currentDateMyFormat = new SimpleDateFormat("dd:MMM:yy HH.mm").format(new Date());
Of course you can reverse the process (from String to Date) by replacing format with parse.
Hope this answers your question because just like Xu before me, I am not sure I understood your question completely ;)
Since you're talking about doing something application-wide, let me remind you to be cautious with any java.text.Format subclass (including DateFormat, SimpleDateFormat, etc.). As noted in the Javadoc, Formats are generally not thread-safe. I know from personal experience that DateFormats are not.
Therefore, if you're considering setting something up for use across your application, I recommend only defining the format String and sharing it around the application. Instances of a Format class are best-defined in a thread-safe manner, such as on the stack of a method call.

Categories

Resources