I'd love to be able to parse relative strings like now and yesterday and get JodaTime DateTimes. Is it possible? DateTimeFormat.forPattern and doesn't seem to support English relative times and I don't know of any other parsing options in JodaTime.
I should add that I'm using scala-time but can easily drop down to the actual JodaTime classes.
You would need to write either a separate library, or a DateTimeParser. DateTimeParser is the interface used internally by Joda-Time to parse text. Anyone can implement it and plug it directly into the Joda-Time parsing system using DateTimeFormatterBuilder.
Let's see here - "now", "yesterday", "today", "tomorrow". Is that about it? :-)
JodaTime won't parse them for you but it should be trivial enough to write your own function (or enum) to do so; you can even throw in stuff like "day after tomorrow" if you feel like it.
"Now" seems to be the only value for which DateTime would be appropriate, though - all others look more like LocalDate (or, possibly, DateMidnight) to me.
Related
I came to know that DateTimeFormatter has two implementation for formatting the date.
Pattern.format(date)
Date.format(pattern)
public static void main(String[] args) {
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDate date = LocalDate.now();
String dateFormatText = date.format(pattern);
String patternFormatText = pattern.format(date);
System.out.println(dateFormatText);
System.out.println(patternFormatText);
}
Both the SysOut prints the same value.
The Oracle docs examples uses Date.format method, whereas I can see many tech blogs using the Pattern.format method.
Can anyone explain me what is the difference and which is best to use?
Source Code Demo : Here
Though opinion-based I will try an answer.
As Stephen C has already documented, the two forms are equivalent.
Which is best? As so often in programming the answer is: It‘s best to write what will be least surprising to those reading your code.
So what will be least surprising? I am sure that the answer varies. Your organization will — consciously or unconsciously — build a tradition for what you are doing, and the least surprising will be to follow that tradition.
Points of each option
I’d also like to take a look at some thinkable reasons why both options have crept into java.time. This may give us some further thoughts on advantages of one or the other.
And since I don’t do mind reading, it’s guesswork. I think that the form date.format(formatter) was formed with inspiration from at least two sides:
It’s parallel to date.toString(), which with java.time we also often use for formatting a date-time object to a string. In Joda-Time, the predecessor of java.time, we even had the same method name: date.toString(formatter).
It’s somehow parallel to DateType.parse(string, formatter), which is what we use for the opposite operation, converting the string to a date-time object. For example LocalDate.parse("08/04/2021", pattern). This form in turn is necessary with the design of java.time. formatter.parse(string) wouldn’t know whether to parse into a LocalDate, an Instant, a ZonedDateTime or one of the many other date-time types of java.time. (The form pattern.parse("08/04/2021", LocalDate::from) exists as an alternative, though, and is sometimes necessary, but not often used.)
And I may be missing something, but one reason why many tech blogs use formatter.format(date) is inspiration from the now obsolete SimpleDateFormat that consistently used format.format(date). I cannot completely escape the thought that maybe those bloggers have not fully gone into the java.time way of thinking.
Can anyone explain me what is the difference?
There is no significant difference.
The javadoc for LocalDateTime.format says:
public String format(DateTimeFormatter formatter)
Formats this date-time using the specified formatter.
This date-time will be passed to the formatter to produce a string.
In other words, LocalDateTime.format calls DateTimeFormatter.format.
... and which is best to use?
Neither is "best".
It is up to you decide which form expresses your intention more clearly. Do you want to say:
"LocalDateTime: format yourself with this formatter", or
"DateTimeFormatter: format this temporal value".
I want to define a pattern for the Java SimpleDaterFormat to parse existing strings.
The existing dates look like this: 2011-05-02T13:40:00+02:00.
I tried with different patterns, but I got ParseExceptions. The problem seems to be the timezone format.
Printing the pattern in Java:
yyyy-MM-dd'T'HH:mm:ssZ
2012-03-14T15:40:44+0100
yyyy-MM-dd'T'HH:mm:ssz
2012-03-14T15:41:58MEZ
But how can I get
???
2011-05-02T13:40:00+02:00
I'm using Java 6, not Java 7.
If you can use Java 7 or newer, you can use the XXX pattern to get the timezone to look like +02:00:
yyyy-MM-dd'T'HH:mm:ssXXX
Otherwise you might have to manipulate the date string to remove the colon from the timezone before parsing it.
I know it's a bit old question, but someone else might benefit from my hint.
You can use JodaTime. As library documentation stands:
Zone: 'Z' outputs offset without a colon, 'ZZ' outputs the offset with
a colon, 'ZZZ' or more outputs the zone id.
You can use it as well with java 6. You have more examples in this question
Which is the right way to compare Time in Java?
I mean java.sql.Time.
Or is there a better way we can compare time in Joda Time?
If you can use Joda Time do so. Convert all sql types to Joda equivalents at the persistence layer and then work with Joda objects in your business logic. You won't regret it, believe me.
LocalTime is probably the object you want to use then you can use compareTo(), isAfter(), isBefore(). Its also really easy to merge this into a full DateTime if necessary.
Well aware of performance and thread issues with SimpleDateFormat, I decided to go with FastDateFormat, until I realized that FastDateFormat is for formatting only, no parsing!
Is there an alternative to FastDateFormat, that is ready to use out of the box and much faster than SimpleDateFormat?
I believe FastDateFormat is one of the faster ones, so anything that is about as fast would do.
Just curious , any idea why FastDateFormat does not support parsing? Doesn't it seriously limit its use?
Note that since commons-lang 3.2, FastDateFormat supports parsing as well as printing.
See: http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/time/FastDateFormat.html
At a best guess, it's to keep FastDateFormat... well... fast, by limiting it to display only.
Apache Commons DateUtils has a parseDate function, but that uses SimpleDateFormat internally.
An alternative is to use the JodaTime library. It's a complete replacement for dealing with DateFormat, Date, and Calendar objects.
JodaTime has a DateTimeFormatter that can be used to create DateTime objects (JodaTime's equivalent of Java's Date objects) from strings.
An example of how to use it is like this:
String strInputDateTime = "2010-12-27"; // An example, this would really come from outside
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");
DateTime dt = fmt.parseDateTime(strInputDateTime);
I don't know if this is really any faster than SimpleDateFormat, though.
Found something interesting here of this case in Android:
http://andmob.wikidot.com/faq-simpletimeformat
SimpleDateFormat, the first time you
try parsing (or, presumably,
formatting) a date, will load in all
the timezone data for your locale.
This will take 2-3 seconds. It is
hoped that this will be fixed in some
future edition of Android.
In the interim, consider using
AsyncTask to "warm up"
SimpleDateFormat in your process
before you need it. Just parse some
date in the AsyncTask doInBackground()
to get it to load the timezones
sometime when it will not impact the
user so much. Once initialized in your
process, SimpleDateFormat will run
quickly until your process is
terminated.
As of Java 8, one can use DateTimeFormatter along with the the Java 8 Time API to both parse and format dates. From the documentation:
This class is immutable and thread-safe.
It's recommended to use this class if possible for new work going forward instead of using SimpleDateFormat.
The 'problem' with SimpleDateFormat is not performance, its thread safety.
If you have thousands of threads and synchronizing is not an issue use synchronized (you can also pool the instances to alleviate this a little)
If you have a reasonable amount of threads the recommended way is to have a separate instance for each SimpleDateFormat.
UPDATE
As of Java 8, just use DateTimeFormatter. It is immutable, thread safe, faster, and more flexible. (It also offers nice features like default patterns for ISO-8601 date/time strings.)
Do you really need to parse dates that quickly? Have you tested SimpleDateFormat and found it too slow for your needs?
Note, there are a variety of ways to cache slow-to-construct, non-thread-safe class instances (e.g. ThreadLocal, pools).
Is it possible in easy way to convert JRuby Time/DataTime/Data into java.util.Calendar including the timezone?
On #jruby I was given such code cal.set_time_in_millis(time.to_i) but I lost information about timezone in betwean. So the more specific question is how to convert the timezone but I prefered to ask more broad questin in case there is simpler way.
You can use the #to_java method to convert a Ruby time object to a java.util.Date:
require 'java'
Time.now.to_java
Note this coersion happens automatically when passing Ruby objects to Java methods.
I get known that the Time does not store timezone so what is returned by Time.now.zone is local timezone.
Therefore it is simple to convert to java.util.Data:
data = java.util.Date.new(date.to_i*1000)