I'm working on a java class that I will use with Pervasive Data Profiler that needs to check if a Date String will work with .NET's DateTime.Parse.
Is there an equivalent class or 3rd party library that can give me this functionality that is very close to .NET's DateTime.Parse?
I would need it to be able to handle a broad range of date formats.
ex. "12/20/2008", "1/1/08", "5/10/2009 12:46:00 AM", "5/10/2009 17:46:00"
See parse method in DateFormat Class. Here is a sample
DateFormat df = new SimpleDateFormat ("yyyy-MM-dd");
Date date = df.parse("2001-01-01");
Check the DateFormat.parse(String) methods of the DateFormat class.
Also, the class Date has two deprecated methods that parse strings into Date objects, however the use of the Date class in general is not recommended. It has been replaced by the Calendar class.
Use DateFormat:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse("2010-03-15");
SimpleDateFormat (is very handy. But... if you really want to use something more powerful -and consider it's really worth- you can use Joda Time. It's a very powerful, yet easy-to-use library. Indeed there's a proposal to make a new standard library very similar to it.
Related
From reading about them I understand that the android class is a utility class made for convenience only, and provide nothing that SimpleDateFormat doesn't provide. Is there any significance to the android class? Is it better practice to use it (if yes, why)? My goal is to display a Date object in an android app (obviously). Here it is:
private Date date;
public String getDateString(String formatStr){
return new SimpleDateFormat(formatStr).format(date);
}
would it be better to use android.text.format.DateFormat like this:
public String getDateString(String formatStr){
return android.text.format.DateFormat.format(formatStr, date);
}
or perhaps none of the two, but a different way would be best? thanks in advance.
Copying my answer from https://stackoverflow.com/a/27116266/642160 :
As far as I can tell, android.text.format.DateFormat has some of the functionality from java.text.DateFormat, some of the functionality from java.text.SimpleDateFormat, and some extra functionality of its own.
Most notably:
The java SimpleDateFormat allows construction of arbitrary non-localized formats.
The java DateFormat allows construction of three localized formats each for dates and times, via its factory methods.
The android DateFormat allows most of the above (arbitrary formats and a smaller number of localized formats), but also provides getBestDateTimePattern which picks a locale-appropriate format string that contains the elements specified with locale-appropriate ordering and punctuation.
So, if you need a localized date/time format other than the three provided by java's DateFormat class, the android DateFormat class is the solution.
Less importantly, but an additional convenience: the android DateFormat methods can take a Calendar or long milliseconds directly, instead of requiring a Date object. I always prefer working with Calendar or long over Date. Also, it properly respects the timezone of the Calendar object -- whereas getting a Date from a Calendar and passing that along to the formatter loses the timezone information. (Nothing you can't get around via java DateFormat's setCalendar method, but it's nice to not have to.)
Finally, and least importantly, some of the methods of the Android DateFormat don't actually construct a formatter, you just construct a format string. All of this class's methods are static. The methods do that construct a DateFormat actually construct a java DateFormat!
I believe the answer lies here:
This class' factory methods return appropriately-localized DateFormat
instances, suitable for both formatting and parsing dates.
I don't think the SimpleDateFormat provide appropriately-localized formats.
I'm parsing third party log files containing date/time using Joda. The date/time is in one of two different formats, depending on the age of the log files I'm parsing.
Currently I have code like this:
try {
return DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss").parseDateTime(datePart);
} catch (IllegalArgumentException e) {
return DateTimeFormat.forPattern("E, MMM dd, yyyy HH:mm").parseDateTime(datePart);
}
This works but contravenes Joshua Bloch's advice from Effective Java 2nd Edition (Item 57: Use exceptions only for exceptional conditions). It also makes it hard to determine if an IllegalArgumentException occurs due to a screwed up date/time in a log file.
Can you suggest a nicer approach that doesn't misuse exceptions?
You can create multiple parsers and add them to the builder by using DateTimeFormatterBuilder.append method:
DateTimeParser[] parsers = {
DateTimeFormat.forPattern( "yyyy-MM-dd HH" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd" ).getParser() };
DateTimeFormatter formatter = new DateTimeFormatterBuilder().append( null, parsers ).toFormatter();
DateTime date1 = formatter.parseDateTime( "2010-01-01" );
DateTime date2 = formatter.parseDateTime( "2010-01-01 01" );
Joda-Time supports this by allowing multiple parsers to be specified - DateTimeFormatterBuilder#append
Simply create your two formatters using a builder and call toParser() on each. Then use the builder to combine them using append.
Unfortunately I don't believe Joda Time has any such capabilities. It would be nice to have a "tryParseDateTime" method, but it doesn't exist.
I suggest you isolate this behaviour into your own class (one which takes a list of patterns, and will try each in turn) so that the ugliness is only in one place. If this is causing performance issues, you might want to try to use some heuristics to guess which format to try first. For example, in your case if the string starts with a digit then it's probably the first pattern.
Note that DateTimeFormatters in Joda Time are conventionally immutable - you shouldn't be creating a new one each time you want to parse a line. Create them once and reuse them.
I want to save a Date object to a readable string (for example 22/10/2009 21:13:14) that is also parsable back to a Date object.
I have tried many things and the best I could find was to use DateFormater for parsing and formating but it has a setback. When you format a date you lose seconds information. I tried to find if there is an option to format it and display the seconds (even better would be to the millisecond level since that's the resolution the Date object allows you to have) but I came up short.
Any ideas?
Take a look at java.text.SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS");
Date dt = new Date();
String S = sdf.format(dt); // formats to 09/23/2009 13:53:28.238
Date dt2 = sdf.parse(S); // parses back
SimpleDateFormat can format and parse a date based on a very simple pattern system that include second and even milliseconds.
Other answers are all good.
But when doing this kind of thing please pick a format that sorts properly when coded as a string.... "yyyy/MM/dd HH:mm:ss" is fine. It always astounds me when software engineers pick a date format which doesn't sort in the obvious, convenient way.
You'll save your fellow developers a lot of pain at some distant point in the future - think of it as good karma :-)
ISO 8601
Use ISO 8601 format.
It’s flexible, it includes seconds and fraction of second if there are any, but you may also leave them out if they are 0.
It’s standard, so more and more tools format and parse it. Great for serialization for storage or data interchange.
It goes like 2009-10-22T21:13:14, I should say it’s pretty human-readable (though the T in the middle that denotes the start of the time part may feel unusual at first).
The strings sort properly, as mikera requested in another answer, as long as the years are in the four-digit range from 1000 through 9999.
The classes of java.time, the modern Java date and time API, as well as those of Joda Time parse ISO 8601 as their default, that is, without any explicit formatter, and produce the same format from their toString methods.
A modest demonstration of using java.time:
LocalDateTime dateTime = LocalDateTime.of(2009, 10, 22, 21, 13, 14);
String readableString = dateTime.toString();
System.out.println(readableString);
LocalDateTime parsedBack = LocalDateTime.parse(readableString);
System.out.println(parsedBack);
This prints two identical lines:
2009-10-22T21:13:14
2009-10-22T21:13:14
The latter System.out.println() call implicitly calls toString() once more, so this shouldn’t surprise.
A little off-topic, but I always feel the need to remind people that DateFormat and SimpleDateFormat are not thread safe! The Sun documentation clearly states this, but I keep finding code out in the wild where people stick a SimpleDateFormat in a static ...
If you want to do it a little simpler, and be spared from making your own DateFormat that most other Answers involve, you can leverage the default format in java.time.Instant:
(new Date()).toInstant.toString();
Can somebody please explain to me how I can convert
2009-10-27 14:36:59.580250
into
27.10.2009, 14:36 ?
The first date is available as a string and the second one should be a string as well ;) Up to now I'm not so into date conversion within Java...
Thanks in advance!
You can use java.text.SimpleDateFormat for this. First step is to parse the first string into a java.util.Date object using SimpleDateFormat based on the pattern of the first string. Next step is to format the obtained java.util.Date object into a string based on the pattern of the second string. For example:
String datestring1 = "2009-10-27 14:36:59.580250";
Date date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(datestring1);
String datestring2 = new SimpleDateFormat("dd.MM.yyyy HH:mm").format(date1);
System.out.println(datestring2);
Edit: I've removed the .SSSSSS part from the first pattern because it failed. But in my opinion it should in theory have worked with "yyyy-MM-dd HH:mm:ss.SSS" and "yyyy-MM-dd HH:mm:ss.SSSSSS" as well, but it is calculating them as seconds! I consider this as a buggy implementation in SimpleDateFormat. The JodaTime handles the millis/micros perfectly with those patterns.
You can use SimpleDateFormat. Although there's no format specification for micro-seconds (the last fragment of your input), you can make use of the fact that the parser ignores the rest of the string if it has already managed to match the configured pattern:
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm");
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
System.out.println(formatter.format(parser.parse("2009-10-27 14:36:59.580250")));
The parser will in this case simply ignore the last part ":59.580250" of the input string.
Check out SimpleDateFormat. You can use this to both parse and format. I would suggest parsing the above into a Date object using one SimpleDateFormat, and then formatting to a String using a 2nd SimpleDateFormat.
Note that SimpleDateFormat suffers from threading issues, and so if you're using this in a threaded environment, either create new SimpleDateFormats rather than used static versions, or use the corresponding but thread-safe classes in Joda.
Keep in mind when you do this that you are losing precision. Depending on your specific application, this may or may not matter.
If you already have the original date saved somewhere, this is not an issue. However, if the source date is from a transient source (e.g., streaming in from a physical sensor of some sort), it may be a good idea to persist the interim Date object (output of SimpleDateFormat#parse(String)) somewhere.
Just thought I'd point that out.
Is there a way to format a UTC time into any arbitrary string format I want in java? Basically I was thinking of having some class take the timestamp and I pass it is string telling it how I want it formated, and it returns the formatted string for me. Is there a way to do this?
The java.text.SimpleDateFormat class provides formatting and parsing for dates in a locale-sensitive manner.
The javadoc header for SimpleDateFormat is a good source of detailed information. There is also a Java Tutorial with example usages.
The DateFormat class or SimpleDateFormat should get you there. For example, http://www.epochconverter.com/ lists the following example to convert a epoch time to human readable timestamp with Java:
String date = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000));
Date instances are insufficient for some purposes.
Use Joda Time instead.
Joda time integrates with Hibernate and other databases.
One gotcha to be aware of is that SimpleDateFormat is NOT thread-safe. Do not put it in a static field and use it from multiple threads concurrently.