Read date in Java with Scanner

55,887

Solution 1

For scanner: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html The next() and hasNext() methods first skip any input that matches the delimiter pattern, and then attempt to return the next token. nextLine advances this scanner past the current line and returns the input that was skipped.

Use a date DateFormat to parse string to date; I suppose setDate expects a Date

    Scanner scanner = new Scanner("Monday 12 December 2013,a, other fields");
    scanner.useDelimiter(",");

    String dateString = scanner.next();
    //System.out.println(dateString);

    DateFormat formatter = new SimpleDateFormat("EEEE dd MMM yyyy");
    Date date = formatter.parse(dateString);
    //System.out.println(date);
    sale.setDate(sc.next()); 

Solution 2

Even i faced the same issue but after that able to resolve with below mentioned code. Hope it helps.

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

Solution 3

Another way to do this is by utilizing LocalDateTime and DateTimeFormatter from Java 8. Found this example here:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(yyyy-MM-dd HH:mm:ss.SSS);
LocalDateTime dateTime = LocalDateTime.parse(s.next(), formatter);
System.out.println(dateTime.format(formatter));

Check the link for an in-depth explanation!

Share:
55,887
HpdsbuΖt
Author by

HpdsbuΖt

Updated on July 10, 2020

Comments

  • HpdsbuΖt
    HpdsbuΖt almost 4 years

    Well, i'm trying to read a string with scanner in the same line. For exapme ,i want to read: Monday 12 December 2013 and this needs to be put in a String variable so as to help me print it.

    In my code there is this:

    sale.setDate(sc.next());
    

    with the command sc.next() i can't put a date in the form i mentioned but only in a form like: mmddyy or mm/dd/yyyy

    How can i read a whole string like "Monday 12 December 2013 " ?

    There is a confusion for me about sc.next sc.nextLine etc..