Is there any direct way to set a date to a variable but as an input? I mean that i don't know the date at design time, the user should give it. I tried the following code but it doesn't work: Calendar myDate=new GregorianCalendar(int year, int month , int day);
-
1Look at the Scanner class for handling user input. – Alexis C. Dec 20 '14 at 13:23
-
1I do not understand why you mean by "direct way to set a date to a variable but as an input". Can you be more specific? – kingspeech Dec 20 '14 at 13:28
-
1I mean if there is a method defined by java takes arguments as variabels and then know sthe values of them at the run time. – user3159060 Dec 20 '14 at 14:02
-
3FYI, the [`GregorianCalendar`](https://docs.oracle.com/javase/9/docs/api/java/util/GregorianCalendar.html) class is now legacy, replaced by [`ZonedDateTime`](https://docs.oracle.com/javase/9/docs/api/java/time/ZonedDateTime.html) in Java 8 and later. Or use [`LocalDate`](https://docs.oracle.com/javase/9/docs/api/java/time/LocalDate.html) if you want only the year-month-day without time of day. `LocalDate.of( 2018 , 1 , 23 )` = January 23, 2018. – Basil Bourque Feb 05 '18 at 22:14
9 Answers
tl;dr
LocalDate.of( 2026 , 1 , 23 ) // Pass: ( year , month , day )
java.time
Some other Answers are correct in showing how to gather input from the user, but use the troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
LocalDate
For a date-only value without time-of-day and without time zone, use the LocalDate
class.
LocalDate ld = LocalDate.of( 2026 , 1 , 23 );
Parse your input strings as integers as discussed here: How do I convert a String to an int in Java?
int y = Integer.parseInt( yearInput );
int m = Integer.parseInt( monthInput ); // 1-12 for January-December.
int d = Integer.parseInt( dayInput );
LocalDate ld = LocalDate.of( y , m , d );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
- Java SE 8, Java SE 9, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.

- 303,325
- 100
- 852
- 1,154
Try the following code. I am parsing the entered String to make a Date
// To take the input
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the Date ");
String date = scanner.next();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
Date date2=null;
try {
//Parsing the String
date2 = dateFormat.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(date2);

- 1,766
- 2
- 18
- 38
-
1Does this way make a real date ? I mean if i insert a wrong date does it accept it ? – user3159060 Dec 20 '14 at 14:27
-
1yes ! It does. Please make sure that you are entering the date in right format . I mean for above example If I'll enter : 35-MAR-1992 then result will be : Sat Apr 04 00:00:00 PST 1992 – sitakant Dec 21 '14 at 18:51
-
1FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes built into Java 8 & Java 9. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Feb 05 '18 at 22:13
java.time
I recommend that you use java.time, the modern Java date and time API, for your date work. The Date
and SimpleDateFormat
classes used in most of the other answers are poorly designed and long outdated. Don’t use them.
I further suggest that the user wants to enter the date in a short format specific to his or her locale. For this purpose I first declare a few constants:
private static final Locale defaultFormattingLocale
= Locale.getDefault(Locale.Category.FORMAT);
private static final String defaultDateFormat = DateTimeFormatterBuilder
.getLocalizedDateTimePattern(FormatStyle.SHORT, null,
IsoChronology.INSTANCE, defaultFormattingLocale);
private static final DateTimeFormatter dateFormatter
= DateTimeFormatter.ofPattern(defaultDateFormat, defaultFormattingLocale);
Now prompting for and reading the date goes like this:
Scanner inputScanner = new Scanner(System.in);
LocalDate sampleDate
= Year.now().minusYears(1).atMonth(Month.NOVEMBER).atDay(26);
System.out.println("Enter date in " + defaultDateFormat
+ " format, for example " + sampleDate.format(dateFormatter));
String dateString = inputScanner.nextLine();
try {
LocalDate inputDate = LocalDate.parse(dateString, dateFormatter);
System.out.println("Date entered was " + inputDate);
} catch (DateTimeParseException dtpe) {
System.out.println("Invalid date: " + dateString);
}
Sample session in US locale:
Enter date in M/d/yy format, for example 11/26/20
2/9/21
Date entered was 2021-02-09
Sample session in Danish locale:
Enter date in dd/MM/y format, for example 26/11/2020
9/februar/2021
Invalid date: 9/februar/2021
In the last case you will probably want to allow the user to try again. I am leaving that to you.
Link
Oracle tutorial: Date Time explaining how to use java.time.

- 81,772
- 15
- 137
- 161
-
3Nice! **For future visitors:** In the code given above, the `Locale` used with `dateFormatter` doesn't necessarily have to be the same one as used to obtain `defaultDateFormat`. For example, `String format = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.FULL, null, IsoChronology.INSTANCE, Locale.FRANCE); LocalDate now = LocalDate.now(); System.out.println(now.format(DateTimeFormatter.ofPattern(format, Locale.ENGLISH))); System.out.println(now.format(DateTimeFormatter.ofPattern(format, Locale.FRANCE)));` – Arvind Kumar Avinash Feb 06 '21 at 10:24
Maybe you can try my simple code below :
SimpleDateFormat dateInput = new SimpleDateFormat("yyyy-MM-dd");
Scanner input = new Scanner(System.in);
String strDate = input.nextLine();
try
{
Date date = dateInput.parse(strDate);
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(date));
}
catch (ParseException e)
{
System.out.println("Parce Exception");
}

- 21
- 1
-
1Thanks for wanting to contribute. Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. We have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Feb 06 '21 at 07:19
Check this out:)
ZoneId defaultZoneId = ZoneId.systemDefault();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the DOB: ");
String dobString = scanner.nextLine();
LocalDate dobLocal = LocalDate.parse(dobString);
Date dob = Date.from(dobLocal.atStartOfDay(defaultZoneId).toInstant());
System.out.println(dob);
Simple project GitHub Repo: https://github.com/lojithv/Java-Enter-Student-Details.git
You should enter dob like this : yyyy-mm-dd
Done:)

- 906
- 1
- 10
- 8
I have modified @SK08 answer and created a method which takes year, month and date as input from the user and returns date.
Scanner scanner = new Scanner(System.in);
String str[] = {"year", "month", "day" };
String date = "";
for(int i=0; i<3; i++) {
System.out.println("Enter " + str[i] + ": ");
date = date + scanner.next() + "/";
}
date = date.substring(0, date.length()-1);
System.out.println("date: "+ date);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date parsedDate = null;
try {
parsedDate = dateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return parsedDate;

- 4,263
- 1
- 34
- 39
This is a repost of a comment. I give Arvind Kumar Avinash full credit. @arvindkumaravinash "Nice! For future visitors: In the code given above, the Locale used with dateFormatter doesn't necessarily have to be the same one as used to obtain defaultDateFormat. For example,
String format = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.FULL, null, IsoChronology.INSTANCE, Locale.FRANCE);
LocalDate now = LocalDate.now();
System.out.println(
now.format(DateTimeFormatter.ofPattern(format, Locale.ENGLISH)));
System.out.println(
now.format(DateTimeFormatter.ofPattern(format, Locale.FRANCE)));
" For Americans, be sure to replace FRANCE with US, the British use UK, and so on. here is a list of currently used countries. https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html
Also be sure to import all packages necessary separately, because time* will not work for this. So these essentially
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
import java.time.format.FormatStyle;
import java.time.chrono.IsoChronology;

- 81,772
- 15
- 137
- 161

- 21
- 10
-
I just want arvind to get some credit and include that if you are not in FRANCE you need to put the correct country. @arvind – oofalladeez343 Oct 27 '21 at 19:15
This should work fine and you can validate the date as well using setlenient function-
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;
public class Datinput {
public static void main(String args[]) {
int n;
ArrayList<String> al = new ArrayList<String>();
Scanner in = new Scanner(System.in);
n = in.nextInt();
String da[] = new String[n];
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setLenient(false);
Date date[] = new Date[n];
in.nextLine();
for (int i = 0; i < da.length; i++) {
da[i] = in.nextLine();
}
for (int i = 0; i < da.length; i++) {
try {
date[i] = sdf.parse(da[i]);
} catch (ParseException e) {
e.printStackTrace();
}
}
in.close();
}
}

- 41
- 10
This is working I tried!
package javaapplication2;
//@author Ibrahim Yesilay
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class JavaApplication2 {
public static void main(String[] args) throws ParseException {
Scanner giris = new Scanner(System.in);
System.out.println("gün:");
int d = giris.nextInt();
System.out.println("ay:");
int m = giris.nextInt();
System.out.println("yil:");
int y = giris.nextInt();
String tarih;
tarih = Integer.toString(d) + "/" + Integer.toString(m) + "/" + Integer.toString(y);
System.out.println("Tarih : " + tarih);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date girilentarih = null;
girilentarih = dateFormat.parse(tarih);
System.out.println(dateFormat.format(girilentarih));
}
}