Chris Rahmé
Chris Rahmé

Reputation: 368

java.sql.Date not printing correct date

The following code prints out "3920-06-02", but it's supposed to be "2020-05-02". What did I do wrong?

import java.sql.Date
// ...

public static void main(String[] args) {
    Date May0220 = new Date(2020,  5,  2);
    System.out.println(May0220.toString());
}

I want to use java.sql and not java.util.

Upvotes: 3

Views: 988

Answers (2)

Kaviranga
Kaviranga

Reputation: 666

You can use this reference How to Get Current Date and Time in Java to get the output like you expected . I've Just modified the code in the example by removing the time part.

The librararies are java.time.format.DateTimeFormatter; and java.time.LocalDateTime.

import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;  
public class PrintDateTime {  
  public static void main(String[] args) {  
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    LocalDateTime now = LocalDateTime.now();
    System.out.println(dtf.format(now));
 }  
}  

Hope you find it useful !

Upvotes: 1

rohan1122
rohan1122

Reputation: 130

It seems as if java.sql.Date; uses the year from 1900, and uses array like indexing for the month, so it's off one less than what it should be.

This is what I did to get your desired result.

public static void main(String[] args) 
{
    Date May0220 = new Date(2020 - 1900, 5 - 1, 2);
    System.out.println(May0220+"");
}

A more general form would be

{
    int year = 2020;
    int month = 5;
    Date date = new Date(year - 1900, month - 1, 2);
    System.out.println(date+"");
}

Good Luck!

Upvotes: 2

Related Questions