Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a temporary copy of a Calendar object in Java

Tags:

java

calendar

I need to figure out how to create a temporary Calendar object (a copy of a "permanent" calendar that already exists) so that I can manipulate the copy: tempCal.add(unit, value). I need to keep the original calendar object unchanged, so I really don't want to call add(unit, value) on it directly.

Since none of my attempts at creating a copy actually worked, my current ugly hack is to call permanentCal.add(unit, value), display the desired results, then call permanentCal.add (unit, -value) — which just seems, uncool.

like image 795
Rich Avatar asked May 21 '13 20:05

Rich


People also ask

What is Calendar getInstance () in Java?

The getInstance() method in Calendar class is used to get a calendar using the current time zone and locale of the system. Syntax: public static Calendar getInstance() Parameters: The method does not take any parameters. Return Value: The method returns the calendar.


2 Answers

java.util.Calendar has a clone method, you could use that. All data in it is made of primitives, so you will not run into troubles.

Have a look at these answers:

  • Defensive copy of Calendar
  • Quickest way to clone a GregorianCalendar?
like image 57
Alberto Zaccagni Avatar answered Sep 29 '22 14:09

Alberto Zaccagni


(Not for Android)

Switch to java 8's immutable LocalDateTime, the successor of Calendar/Date. This API is an immense improvement, may be a bit overwhelming at first.

There a method like minusDays(long) will return a new date. Which makes for thread-safeness and all. For instance being able to share a value without fear of someone altering it.

like image 23
Joop Eggen Avatar answered Sep 29 '22 12:09

Joop Eggen