What’s the right way to create a date in Java ?

What’s the right way to create a date in Java ?

Asked on December 22, 2018 in Java.
Add Comment


  • 5 Answer(s)

    Use  SimpleDateFormat.

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date d = sdf.parse("21/12/2012");
    
    Answered on December 22, 2018.
    Add Comment

    Instead of using Java’s Date or Calendar classes try to use joda.time.

    The example code,

    DateTime aDate = new DateTime(year, month, day, hour, minute, second);
    DateTime anotherDate = new DateTime(anotherYear, anotherMonth, anotherDay, ...);
    if (aDate.isAfter(anotherDate)) {...}
    DateTime yearFromADate = aDate.plusYears(1);
    
    Answered on December 22, 2018.
    Add Comment

    Try to use joda-time function. It would be better than other java classes.

    Answered on December 22, 2018.
    Add Comment
    1. Date() : Creates date object representing current date and time.
    2. Date(long milliseconds) : Creates a date object for the given milliseconds since January 1, 1970, 00:00:00 GMT.
    3. Date(int year, int month, int date)
    4. Date(int year, int month, int date, int hrs, int min)
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date d = sdf.parse("21/12/2012");
    Answered on January 16, 2019.
    Add Comment
    Java program to demonstrate constuctors of Date
    import java.util.*;
     
    public class Main
    {
        public static void main(String[] args)
        {
            Date d1 = new Date();
            System.out.println("Current date is " + d1);
            Date d2 = new Date(2323223232L);
            System.out.println("Date represented is "+ d2 );
        }
    }

    Output:

    Current date is Tue Jul 12 18:35:37 IST 2016
    Date represented is Wed Jan 28 02:50:23 IST 1970IST 1970
    
    
    Answered on January 16, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.