简体   繁体   中英

Java - Format a date given day, month and year integers

I would like to format three numbers representing year, month and day using the Java date format specifiers. I know I can create a Date object and use the built in formatting functions, but I would like to know if there is any way to avoid creating the intermediate date object. Given the volumes of data that I am expecting, the garbage collection overhead is something that I always have to keep in mind.

Essentially I am looking for library function suggestions or similar.

Edit: The idea is that the user can specify the format parameter. If they don't I am falling back to a standard format like that suggested in the comment. So I will get a string like "YYYY-DD-MM" and have to use that as appropriate.

如果您担心垃圾收集和对象创建,为什么不在类或系统中保留单个Calendar实例,并使用静态/同步方法将其用于所有格式化目的?

In that case, see:

http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#dt

That will allow you to parse dates with a custom format. I think this is probably what SimpleDateFormatt uses under the bonnet. In reference to your concerns about garbage collection, have you actually tried it? The following demo code executes in one second on my machine (logging and console output omitted as this will unfairly slow it down):

long startTime = System.currentTimeMillis();
Calendar c = Calendar.getInstance();
DateFormat formatter = SimpleDateFormat.getDateInstance(DateFormat.SHORT);
Random rand = new Random();
for (int i = 0; i < 1000000; ++i)
{
  c.set(Calendar.HOUR_OF_DAY, rand.nextInt(24) + 1);
  c.set(Calendar.DAY_OF_MONTH, rand.nextInt(28) + 1);
  c.set(Calendar.MONTH, rand.nextInt(12) + 1);
  c.set(Calendar.YEAR, rand.nextInt(2015) + 1);
  formatter.format(c.getTime());
}

long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println("Time taken: " + TimeUnit.MILLISECONDS.toSeconds(totalTime));

tl;dr

In extreme data loads where you want to minimize object creation, keep your DateTimeFormatter object(s) around for re-use. That class is inherently thread-safe, so you may re-use across threads.

java.time

Some years ago, the troublesome date-time classes such as Date and Calendar and SimpleDateFormat were supplanted entirely by the modern java.time classes defined in JSR 310.

One of the many benefits to the java.time classes: They are thread-safe by design, using immutable objects . So you can keep them around for re-use.

LocalDate

For a date-only value, without time-of-day and without time zone, use the LocalDate class.

LocalDate ld = LocalDate.of( 2019 , 1 , 23 ) ;

To generate text in standard ISO 8601 format of YYYY-DD-MM, simply call toString .

String output = ld.toString() ;  // ISO 8601 format.

DateTimeFormatter

For other formats, use the DateTimeFormatter class.

Again, you can safely keep objects of this class around for re-use across threads. Loop through multiple DateTimeFormatter objects, trying each in succession, trapping for DateTimeParseException until one succeeds.

If concerned about efficiency and minimizing object creation because of extreme data loads, be clever about identifying which formatter(s) may be appropriate to a particular input. For example, the length of the string may tell you which formatter to use.

Also, be aware that with the DateTimeFormatterBuilder class, you can specify optional parts. This effectively lets a single formatter parse multiple kinds of inputs.

Let the JVM work for you

Lastly, a caution: Worrying about creating too many objects is almost certainly unwarranted.

The modern JVMs are extremely well-tuned and effective. They commonly have special handling for short-lived objects for efficient disposal. Do not fall into the trap of premature-optimization : Use profiling to prove you have a measurable performance problem before writing squirrelly code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM