Date type in Java scroll forward backward time (with tool class)
Don't say much nonsense, first look at the tool class:
1 ImportJava.text.SimpleDateFormat;2 ImportJava.util.Calendar;3 Importjava.util.Date;4 5 Public classDateroll {6 7 /**8 * Date type forward backward rolling fixed duration9 * Ten * @paramDate One * Enter NULL to represent the time object before the current time adjustment A * @paramI - * need to scroll which field, writing: Year->calendar.year month->calendar.month - * Day->calendar.date->calendar.hour_of_day (24 hour system) the * minutes->calendar.minute seconds->calendar.second milliseconds->calendar.millisecond - * @paramD - * Scroll how much, Forward (formerly) with negative numbers, backward (future) with a positive number - */ + Public StaticDate Dateroll (date date,intIintd) { - //gets the Calendar object and takes the time to pass in +Calendar Calendar =calendar.getinstance (); A calendar.settime (date); at //converts the current time to a fixed length, to a date type assignment - Calendar.add (i, d); - //Convert to date type re-assign value -Date =calendar.gettime (); - returndate; - } in - Public Static voidMain (string[] args) { toSystem.out.println (NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss") +. Format (NewDate ())); -System.out.println (NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss") the. Format (Dateroll (NewDate (), Calendar.second, 1))); * } $}
There are 2 classes of processing time in Java, one is well-known Java.util.Date class and the other is Java.util.Calendar, so what's the difference between them, in the early Java there is no Calendar class, Later people found many bugs in the date class, such as
In the forward rollback time, if the 2018-1-2 rollback 5 days will become 2018-12-28, it is obvious that this is wrong, but because of the early provisions of Java, JDK developers did not directly in the date class, but added a more perfect calendar class
Calendar after a long period of practical use, it is proved that it is complete, calendar also provides a conversion with the date, the scrolling method in this article is based on this idea,
How the date type in Java scrolls forward and backward in time (with tool class)