Java, date from string without pattern - java

I need to get a Date instance from input file. I don't know the date format, but I want to get it from user profile settings.
Te following code does not working:
DateFormat form = DateFormat.getDa​teInstance(DateF​ormat.SHORT, Locale.getDefaul​t());
try {
Date t = form.parse("6/6/2015");
}
unparseable date error
I want to know if there is any way to get date from string without knowing the date string pattern.
I need this date to create MySQL query. Maybe there is another way to build this query without parsing date? I am using Entity Beans.

No. Consider the date "1/2/2015": is that February 1st or January 2nd. Depends on your locale.
Instead, you should be more specific: rather than getting a date formatter for your locale, use SimpleDateFormat with an explicit pattern.

I want to know if there is any way to get data from string without knowing the data string pattern.
Without any more information, this is very error prone. For example, consider "7/6/2015" - does that mean June 7th, or July 6th?
If you know the user's locale, you can do a lot better - for example, you could obtain DateFormat instances for long, medium, short and full date patterns for that locale, and try them one at a time. Bear in mind, however, that depending on where this code is executing, the default locale (as you're using at the moment) may not be the user's locale. You mention the user profile settings - hopefully that already contains a locale.
One alternative is to ask the user to tell you what the format is - maybe provide lots of different examples, and let them pick the one that matches.
Finally, if the file has lots of dates in and you're confident they'll all be in the same format, you could try to parse all of them in each of several different formats - that's likely to reduce the chances of error, as "7/6/2015" becomes unambigious if you've also seen "13/1/2015" for example.

Related

Create calendar from String date without knowing format

I want to create an instance of Calendar with string date coming from server. Now I don't know what format server is sending .
It can be changed for different countries. I know I can ask them to add another key for dateFormat and create Calendar from it. But still I want to know Is there any way to create Calendar Instance without knowing current string date format.
I have gone through this and this. But none fulfill my requirement
This is impossible.
If the server sends the value "1/2/2017", you have no way of knowing if this refers to January 2nd or February 1st.
If the server sends the value "מָחָר", in theory you could realize that this might be a Hebrew translation of the word "tomorrow" (at least, according to Google Translate), but even then, it is not clear whether this is to be taken relative to today or some other date.
If the server sends the value "I want to create an instance of Calendar with string date coming from server", you have no means of creating a date from that, at least using any algorithm that would make sense to people.
And so on.
The only reason a server should return a date in an arbitrary format is if the date would only ever be read by the user who provided the value in the first place and presented as plain text verbatim, without parsing. Otherwise, the server should supply the date in a standardized format, with the UI consuming that date being responsible for formatting it in a user-friendly (and, ideally, locale-aware) fashion.
You're welcome to try to brute-force the problem, iterating over a series of date formats and seeing if any result in a seemingly-valid date. This fails the 1/2/2017 scenario (as there are at least two formats that would return a seemingly-valid date), but perhaps you know enough about the server to narrow down the possible formats to reduce the odds of collisions like this.
The Joda Date & Time API has a date parser which can parse date strings in many formats. Note that some datetime strings can be ambiguous: 10-09-2003 could mean October 9 or September 10.

Full date Validation in Java

I would like to make a validation for date. the date has many formats:
European and American styles. Also, number, shortcut or even the month full name.
I used Date.parse() but it's not accurate and it has many issues. For example: it doesn't pay attention to the leap year. Also, I added "35/02/2008" without giving me any exception.
I tried regular expression but all of what I found has an issue.
None of them cover the whole possibilities.
Please advise!
You should have a look at the Joda Time library: http://www.joda.org/joda-time/userguide.html#Input_and_Output
For example, you can create a DateTimeFormatter, and parse some text using it:
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMdd");
DateTime dt = fmt.parseDateTime(strInputDateTime);
The library allows for constructing complex date time patterns and it has knowledge of leap years etc.
Date validation does not make sense unless you are validating against a specific date format, or (carefully chosen) set of formats. To illustrate, consider this:
23/11/77
Is that a valid date? It depends!
If you are validating against "dd/MM/YY", then yes it is valid.
If you are validating against "MM/dd/YY", then no it isn't.
If you are validating against "dd/MM/YYYY", then it is valid but it doesn't mean what you think it means.
In short validating "any date" irrespective of format make no sense. The above date could be either valid or invalid, and can mean different things.
The fact that people "know" what these dates mean is worrying. In fact, when most people see a date, they interpret according to their own cultural norms ... without realizing that most dates are ambiguous if the format is not specified / agreed.
If you don't want (or aren't allowed) to use third-party libraries and prefer having manual control over validations, split the string using "/" as separators, then making conditions for all needed cases:
String pattern = "yyyy/MM/dd";
DateFormat df = new SimpleDateFormat(pattern);
String strDate = df.format(date);
String[] arrDate = strDate.split("/");
int year = Integer.parseInt(arrDate[0]);
int month = Integer.parseInt(arrDate[1]);
int day = Integer.parseInt(arrDate[2]);
if (month == 2 && day > 28) {
System.out.println("February has 28 days!");
}
// etc ...
If you are using java 8 then you dont need joda. There is an in-build API LocalDateTime similarly for UTC also there is an API.
The issue that the input may come with different format as soon as my app is an analysis tool.
If I wanna do it manually by splitting the date, I have to create a full class in order to check all the possibilities in all different formats.
There's no full regular expression for this issue. How come?

Is there any way to convert date String of any format to millisecond in java?

Is there any function or library which gets a date in milliseconds, given a String?
This question shows how to convert a formatted String to a Date object, but is there any way to do this with an unformatted String?
Basically, the task is impossible. Here's an example:
01/04/2012
In the US, that means January 4th 2012. In Australia, that mean 1st April 2012.
Without knowing where you are and what date formats conventionally mean, it is impossible to accurately map an arbitrary date-like string to a date time value that matches what the user actually meant.
And even if you do know about the relevant local conventions, users have a remarkable propensity to be oblivious to ambiguity. Dealing with that may require deep domain knowledge (or mind reading skills!) to disambiguate the possible meanings.
When you think about it, this is why modern user interfaces typically use a date-picker widget of some kind when the user needs to enter a date / time
first convert the string to Date. From there you can get time in milis using Date.getTime() method

How should date properties be defined in a java class?

I have a simple java object with several date properties and I always seem to change my mind on how to define them. Should the properties be defined as date objects or strings? The object is going to be used in struts 1.3 application with iBatis as the persistence layer and mysql as the database. The database columns are defined as datetime and they can possibly be null and I usually don’t care about the time portion.
public Date getForcastDate();
or
public String getForcastDate();
Most of the existing code base uses strings, but that just doesn’t seem quite right to me.
Keep your dates as Dates. That way you can change formatting depending on locales, check for invalid dates, sort by them etc.
By keeping them as strings you're potentially throwing away data (e.g. milliseconds if your formatter doesn't use them) and definitely behaviour.
Using strong-typing (e.g. keeping them as Dates) will aid in terms of development. Your method signatures become clearer, refactoring using IDE tooling becomes easier etc. Otherwise you end up with APIs that talk in nothing but strings, it's trivial to mix up parameters, and it becomes impossible to work out what's going on.
Tip: Check out Joda-Time as a better alternative to the standard java.util.Date.
I would use Date object because it cleaner to store a Date and convert it to a String when needed. Otherwise you have to hard code a formatted date into a String field.
I would never use Strings in this cas as what would today be 8/3/11 or 3/8/11 or 2011-03-08. This is really a specific case of trying to use the most restrictive type/class possible for a variable. This is so that you can understand its behaviour more fully, both by having a restricted or specialised set of methods and by helping documentation of other classes using it. Using a Date here would allow you to use a Calendar object to add days or months. Conversion to or from a string only needs to be done for input and output.
In practice if they were only dates I would crete my own Date class so could ignore times or use JodaTime which provides easier manipulation than the java Date
In my code I always use the most high level object. In this case I would suggest - Calendar. Here is separate discussion about Date and Calendar. I always think this way - converting Calendar/Date to String is simple - use SimpleDateFormatter. But very often you will need to do something with the date (add several days or hours, subtract a year, handle timezones etc) and then each time you would have to convert it from String to Calendar/Date.
Date if you had to, but java.util.Calendar would probably be more appropriate nowadays. With a String you'd have to worry about format like #jzd mentioned. With Calendar, you can easily switch between formats. Also Calendar lets you get at the date with Calendar.getTime()

How do I create a DateFormat with an optional time argument?

I wish to construct a date format that will optionally have a time argument.
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd [hh:mm]");
Is it also possible to construct a date format object that is capable of parsing different formats? Such as try the current locale but then fall back to ISO-8601 or should I just write multiple date formats if one fails?
UPDATE: Looking back at this question I can see I didn't specify that the reason for multiple date formats was for parsing strings, not for formatting a date, thus ambiguity for formatting date objects wasn't a concern for me. If you take this into account the time portion is or is not included in the parsing string.
SimpleDateFormat won't let you do that. It doesn't support alternatives within a (single) format.
Even if it did, there would a problem. Consider using this
new SimpleDateFormat("yyyy-MM-dd [hh:mm]");
versus using
new SimpleDateFormat("yyyy-MM-dd hh:mm");
new SimpleDateFormat("yyyy-MM-dd ");
In the first case, when I parsed a date against the format, I couldn't tell the difference between "2010-01-01" and "2010-01-01 00:00" by looking at the Date delivered to me. In the 2nd case, I can.
In the first case, when I format a Date with zero in the minutes and seconds fields, it is not clear whether the result should end with "00:00" ... or not. In the second case, this is entirely in the hands of the application.
I guess that what I'm really doing here is raising the issue that dates and date/times mean different things to different people and in different contexts. Sometimes they mean instants and sometimes intervals. Sometimes a lack of expressed precision means imprecision, and sometimes that the precision is implied.
As developers we have to run the line between writing software that is annoyingly picky, and software that makes incorrect assumptions about what the user actually means by a date / time value. The first step in getting it right for the user is understanding the complexity of the problem. Overloading variations into a single format string is (would be) sweeping the problem under the carpet.

Categories

Resources