Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

java.util.calendar 2

Status
Not open for further replies.

nn987

Programmer
Feb 4, 2006
37
GB
thread269-1703513
What is the best way to store a simple date.
Should I just store it as a String or should I go through the process of using java.util.calendar or something similar?

I found this code on the internet and is a good example to work with dates

Code:
import java.util.Calendar;
import java.util.Date;

public class GetTheCurrentTime {
  public static void main( String[] args ) {
    // one way
    long currentTimeInMillis = System.currentTimeMillis();
    Date today = new Date( currentTimeInMillis );
    System.out.println( today );

    // another way
    Calendar cal = Calendar.getInstance();
    today = cal.getTime();
    System.out.println( today );
  }
}
 
I will depend on what are you planning to do with the date: if you want to add days, check if it's in a range or store it in a DB with DateTime type, then it's the way to go.

Cheers,
Dian
 
Hi

Dian said:
[gray](...)[/gray] the it's the way to go.
Missing anything ⇑ here, between "the" and "it's" ? ( My rusty Java says [tt]Calendar[/tt] should go there. )


Feherke.
feherke.ga
 
Actually it was just a missing "n" (post edited).

I was trying to clarify the choice between a String or a Java class. A String is what it is: a chunk of characters, so your program won't distinguish between "01/01/16" and "56/00/98" but if your requirements don't involve validation or manipulation, well, String could be an approach.

In any other cases, objects are the way to do. For a long time [pipe], working with date and time in Java was a nightmare and you had to choose between Date and Calendar with no clear recommendation and an endless debate

With Java 8, the new java.time arrived and brought a unified way to deal with date and time. The brand new LocalDate, LocalTime and LocalDateTime end the the debate and (hopefully) will make everyone work the same way, as shown here.


Cheers,
Dian
 
Hi

I see. Indeed, those new classes seems to be able to do everything a programmer may expect from them. ( Wondering how nice could they play together with [tt]java.sql.Date[/tt], but that is another story. )

Thank you, for the information.

Feherke.
feherke.ga
 
I think this time [pipe] they nailed it and directly added new methods to java.sql.Date:

SQL Date -> Local Date: toLocalDate
Local Date -> SQL Date: valueOf

Cheers,
Dian
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top