user3159060
user3159060

Reputation: 131

How to set a date as input in java?

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);

Upvotes: 8

Views: 139085

Answers (9)

oofalladeez343
oofalladeez343

Reputation: 21

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;

Upvotes: 1

Lojith Vinsuka
Lojith Vinsuka

Reputation: 1051

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

enter image description here

You should enter dob like this : yyyy-mm-dd

Done:)

Upvotes: 2

Anonymous
Anonymous

Reputation: 86232

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.

Upvotes: 3

Ghayuh F P
Ghayuh F P

Reputation: 21

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");
}

Upvotes: 2

Basil Bourque
Basil Bourque

Reputation: 338386

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 );

Table of date-time types in Java, both modern and legacy.


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?

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.

Upvotes: 10

Ibrahim Yesilay
Ibrahim Yesilay

Reputation: 1

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));      
    }   
}

Upvotes: 0

Mohit Miglani
Mohit Miglani

Reputation: 41

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();
    }
}

Upvotes: 0

Vikas
Vikas

Reputation: 4301

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;

Upvotes: 1

sitakant
sitakant

Reputation: 1878

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);

Upvotes: 9

Related Questions