How Make operation on time - java

i have a string like this on my java code:
17:00
I want to make a subtraction using a constant integer
public static final int MAX_DUREE_TRAVAIL_JOUR = 10;
When i do this:
Integer.parseInt("17:00") - ConstantesIntervention.MAX_DUREE_TRAVAIL_JOUR
I have this error:
java.lang.NumberFormatException: For input string: "17:00"
Thx.

What are you expecting to happen? 17:00 is not a valid string representation of an integer.
You probably want to use a SimpleDateFormat to parse the string as a Date and do the time arithmetic on that.
Alternatively, take a look at the JodaTime library which provides much better handling of dates/times.

17:00 cant be to converted to an integer.

Because 17:00 is not a Correct integer.You should divide the string and use Integer.parse() then according to your business logic use those integers.

The answer by Ajai is correct.
Some advice: When working with dates and times, work with dates and times (not strings and integers). Meaning use date-time classes.
Use a good date-time library (not the mess that is java.util.Date/Calendar).
Use Joda-Time 2.3 now.
In the future, with Java 8, consider moving to JSR 310: Date and Time API which supplants the Date/Calendar classes and is inspired by Joda-Time.
P.S. Mercer, Joda-Time even knows how to speak français. See another answer of mine today for an example.

Related

Pattern.format(date) vs Date.fomat(Pattern)?

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".

Milliseconds not appearing in DateFormat.format output

I want to have a date-time string in the "yyyy-MM-dd'T'HH:mm:ss.SSSZ" format.
I wrote the following code snippet:
Date date=Calendar.getInstance().getTime();
String currentDateTimeString = (String) android.text.format.DateFormat.
format("yyyy-MM-dd'T'HH:mm:ss.SSSZ",Calendar.getInstance().getTime());
but I get strings like
"2019-11-08T13:39:33.SSSZ"
also when the format is "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" (with 'Z' escaped).
Patterns are found at https://developer.android.com/reference/java/text/SimpleDateFormat.html#examples
Why milliseconds do not appear?
I know little about Android development, but a quick search in the documentation may give you the answer:
https://developer.android.com/reference/android/text/format/DateFormat
The format methods in this class implement a subset of Unicode UTS #35 patterns. The subset currently supported by this class includes the following format characters: acdEHhLKkLMmsyz. Up to API level 17, only adEhkMmszy were supported. Note that this class incorrectly implements k as if it were H for backwards compatibility.
The Unicode UTS #35 says nothing about milliseconds:
https://unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns
So it seems that formatting milliseconds is not supported.
I would rather use the Java standard classes LocalDateTime and DateTimeFormatter, which do support milliseconds.
https://developer.android.com/reference/java/time/format/DateTimeFormatter.html
[Edited]
After re-reading the question, I think the problem is that you're using DateFormat instead of SimpleDateFormat. The link you've provided does not correspond with the actual class you're using in your code.

Migrating from Joda time to Java 8 DateTime

I could not find an alternative toDateTimeAtStartOfTheDay. For example
DateTime.now().toLocalDate().toDateTimeAtStartOfDay().plusHours(10)
how would I write above code in Java 8's DateTime library?
Closest I came to ZonedDateTime.now().toLocalDate().atStartOfDay() which just prints 2015-07-21T00:00.
I want something like 2015-07-21T00:00:00.000-04:00
If you need the time as a formatted String and you always like to get 10 o'clock of today, then don't bother calculating that time manually and write it into a format pattern:
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T10:00:00.000'XXX");
The meaning of each letter can be found here: JavaDoc of DateTimeFormatter. 'T10:00:00.000' is a fixed string and won't be parsed, just "added" to the returned String.
You can get the formatted time like this:
ZonedDateTime.now().format(format);
The output would be:
2015-07-21T10:00:00.000-04:00
You can use:
LocalDate.now().atStartOfDay().atZone(ZoneId.systemDefault());

Turn ISO 8601 date/time into "x minutes ago" type of string

So I have an ISO 8601 date/time stamp like "2011-04-21T17:07:50-07:00", and I would like to convert it to say something like "23 minutes ago" or something of that sort. Is there a small bit of Java code or a library that would be able to do something like that easily?
Thanks!
What you are looking for is known as fuzzy time. A quick Google on this term found jFuzzyDate
First, parse it into a Date object. Then, make a new Date which will have the current date/time. Then, call the .getTime() methods on both of the Date objects, and subtract. Now you have your time in milliseconds.
You can do your own math from there, because until you start worrying about leap years it's all easy division.
Joda is a great time library and should have all the methods you need to do this: http://joda-time.sourceforge.net/.

Alternatives to FastDateFormat for efficient date parsing?

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

Categories