Read date in Java with Scanner - java

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..

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

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

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!

Try this..
public void readDate() throws Exception{
String dateFormat = "dd/MM/yyyy";
Scanner scanner = new Scanner(System.in);
setDate(new SimpleDateFormat(dateFormat).parse(scanner.nextLine()));
}
public void setDate(Date date){
// do stuff
}
chage the dateFormat as you want..

You have to use nextLine to fetch words with intermediate spaces.
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
Scanner sc=new Scanner(System.in);
System.out.println("enter string for c");
String c=sc.next();
System.out.println("c is "+c);
System.out.println("enter string for d");
String d=sc.next();
System.out.println("d is "+d);
OUTPUT:
enter string for c
abc def
c is abc
enter string for d
d is defabc def|
in the first case abc |def //cursor stays after c
in the second case abc def| //cursor stays after for

I found this question interesting but there is not a fully correct answer, so here is a simple solution to easily read and parse a Date form the Scanner.
The best approch would be to create a method that would do it for you, since Scanner is final, we can only do a toolbox instead of a subclass. But this would be easy to use :
public static Date readDate(Scanner sc, String format){
return new SimpleDateFormat(format).parse(sc.nextLine());
}
This would accept the format and the Scanner, don't manage it here because it would be messy to open a Scanner without closing it (but if you close it, you can't open it again).
Scanner sc = new Scanner(System.in);
ToolBox.readDate(sc, "YYYY-MM-DD");
ToolBox.readDate(sc, "YYYY-MM-DD HH:mm:ss");
ToolBox.readDate(sc, "YYYY-MM-DD");
sc.close();
This could be improved by not recreating a SimpleDateFormat each time but a Scanner is not called that much (you are limit by the user inputs) so this is not that important.

try this one
final Scanner sc = new Scanner(System.in);
final String timeString = sc.next();
final LocalTime time = LocalTime.parse(timeString);

Related

Scanner not storing string as a parsed LocalDateTime correctly

When I am taking in a string variable from the scanner and parsing it to LocalDateTime in the format "yyyy-MM-dd HH:mm" the Scanner saved the input (i.e 2020-10-12 14:30) without the time. I believe the time is being saved into the next variable. However if I input 2020-10-1214:30 without the space, it saves the the variable correctly.
Below is my constructor where the object is being created and the string is being parsed into the localdatetime object.
public computerbooking(String strDAte, String ReturnDate,String computerType,String AssetTag,String StudentId ){
counter++;
this.bookingId = "Book"+counter;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
bookingDateAndTime = bookingDateAndTime.parse(strDAte,formatter);
returnDateAndTime = returnDateAndTime.parse(ReturnDate,formatter);
this.computerType = computerType;
this.AssetTag = AssetTag;
this.StudentId = StudentId;
}
How do I instruct the scanner not to read the space between the date and time to save it correctly
LocalDateTime#parse is a static function. Use LocalDateTime.parse(strDate, formatter) instead of bookingDateAndTime.parse(strDAte,formatter).
Use Scanner#nextLine to scan the full line of input. If you are using Scanner#next, it will scan only up to 2020-10-12 i.e. it will stop scanning as soon as it will come across a whitespace character after 2020-10-12.
Demo:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter date and time: ");
String strDate = scanner.nextLine();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm");
LocalDateTime bookingDateAndTime = LocalDateTime.parse(strDate, formatter);
System.out.println(bookingDateAndTime);
// A custom format
String formatted = bookingDateAndTime.format(DateTimeFormatter.ofPattern("MMM dd uuuu hh:mm a"));
System.out.println(formatted);
}
}
A sample run:
Enter date and time: 2020-10-12 14:30
2020-10-12T14:30
Oct 12 2020 02:30 pm

java use simpledateformat to parse a input String get ParseException, and just because of a space

I input a string likes the SimpleDateFormat pattern asked, but it will be ParseException. I do several tests. If I change space between "dd HH" to "dd-HH", the pattern becomes "yyyy-MM-dd-HH:mm:ss", and it will be successful.
The second test is I write a string directly like
String birthdays = "1998-08-12 12:12:12";
and parse it, it will also successful.
so my conclusion is the space I input is not the same as the space in the pattern. what I used is IntelliJ.
SimpleDateFormat datef = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Scanner sc = new Scanner(System.in);
System.out.println("Please input your birthday. the pattern is " +
"yyyy-MM-dd HH:mm:ss");
String birthday = sc.next();
Date date2 = datef.parse(birthday);
// String birthdays = "1998-08-12 12:12:12";
// Date date2 = datef.parse(birthdays); //this will successful
System.out.println(date2);
Instead of using sc.next() use sc.nextLine()
sc.next() will find the first string till space but nextLine() will accept the entire string including space.
That issue is not because of the space.

How to convert integer YYYYmmDD into YYYY/mm/DD in java [duplicate]

This question already has answers here:
How to convert a String of format yyyymmdd to LocalDate in JodaTime [duplicate]
(1 answer)
Change date format in a Java string
(22 answers)
Good way to convert integer YYYYMMDD into java.util.Date with local time zone
(4 answers)
Closed 3 years ago.
I am trying to process the data from a weather station. I simply want to process and print (for now) the minimum and maximum temperatures each day starting from 2000/01/01 until today 2019/12/12. The weather station gives me the date in an integer yyyymmdd like 20191212 or 20030317. I store this, alongside the minimum and maximum temperatures in an integer array, of about 21000 rows long... I want the date to be displayed in yyyy/mm/dd, like 2019/12/12 or 2003/03/17. How exactly do I go about doing this?
This is my code
import java.io.*;
public class Main {
public static void main(String args[]) {
int rowAmount = 7152; //the amount of rows in the document
int[] temperatures = new int[rowAmount*3]; //makes an array 3 times the size of rowAmount, to fit date, min temp and max temp.
try {
BufferedReader br = new BufferedReader(new FileReader("D:\\20002019minmaxtempbilt.txt")); // Makes the filereader
String fileRead = br.readLine(); // reads first like
int counter = 0; //sets a counter
while (fileRead != null) { // loops until the file ends.
String[] tokenize = fileRead.split(","); //splits the line in 3 segements, date, min temp and max temp. And stores them in following variables
int tempDate = Integer.parseInt(tokenize[0]);
int tempMin = Integer.parseInt(tokenize[1]);
int tempMax = Integer.parseInt(tokenize[2]);
//adds the values to the array
temperatures[counter] = tempDate;
counter++;
temperatures[counter] = tempMin;
counter++;
temperatures[counter] = tempMax;
}
// close file stream
br.close();
}
catch (FileNotFoundException fnfe)
{
System.out.println("file not found");
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
// Displays the entire array, formatted by date neatly, hopefully.
for(int i = 0; i<rowAmount; i =+ 3) {
int tempDate = temperatures[i];
int tempMin = temperatures[i+1];
int tempMax = temperatures[i+2];
drawLine(tempDate, tempMin, tempMax);
}
}
public static void drawLine(int tempDate, int tempMin, int tempMax) {
/*This is where I get stuck. I need to convert tempDate from an int yyyymmdd to either
3 separate integers representing year, month and day; or I need to convert it to a
string that can be printed out yyyy/mm/dd.*/
System.out.printf("");
}
}
Since your date is a String to start with I see no reason to convert it to an Integer first. Using the more current java.time package you can use one formatter to convert from a String to LocalDate and then another to convert back to a String with the right format,
DateTimeFormatter inFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate date = LocalDate.parse(tokenize[0], inFormatter);
DateTimeFormatter outFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
String outStr = outFormatter.format(date);
Since DateTimeFormatter is costly to initialise I would recommend you create both of them before the loop you have for reading the file.
Another way: if the integer value representing the date is stored in an int called date (example value: 20191212), then
int day = date % 100;
int month = (date/ 100) % 100;
int year = date / 10000;
then you can use a Formatter to format the string output that you want.
A problem is that an integer of 20191212 really doesn't represent a date.
I would recommend NOT transforming tempDate into an integer and leaving it as a string.
Edit
Here is an example that uses the Java 8 time package classes: LocalDate, DateTimeFormatter, and DateTimeFormatterBuilder:
package stackoverflow;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
public class ParseStringDate {
public static void main(String... args) {
String dateString = "20191231";
DateTimeFormatter dateTimeFormatterParser = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate localDate = LocalDate.parse(dateString, dateTimeFormatterParser);
System.out.println(localDate);
DateTimeFormatter dateTimeFormatterPrinter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
System.out.println(localDate.format(dateTimeFormatterPrinter));
dateTimeFormatterPrinter = new DateTimeFormatterBuilder()
.appendPattern("yyyy")
.appendLiteral("/")
.appendPattern("MM")
.appendLiteral("/")
.appendPattern("dd").toFormatter();
System.out.println(localDate.format(dateTimeFormatterPrinter));
}
}
Here is an example that uses SimpleDateFormat:
package stackoverflow;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormattingFromString {
public static void main(String... args) throws Exception {
String tempDate = "20191212";
SimpleDateFormat sdf1 = new SimpleDateFormat("YYYYmmdd");
Date date = sdf1.parse(tempDate);
// Now format the above date as needed...
SimpleDateFormat sdf2 = new SimpleDateFormat("YYYY/mm/dd");
System.out.println(sdf2.format(date));
}
}
As pointed out in the comments, SimpleDateFormat and the Date classes are not super great to work with. They are mutable and therefore not thread safe. The new java.time package classes are immutable and therefore thread safe. The new classes are also easier to do date math with and comparisons.
I'd recommend using a DateFormat object, taking advantage of the parse(String) and format(Date) methods.

Getting AM/PM information from LocalDateTime instance

I am taking time input from user as a String in Java and then converting it to LocalDateTime object and saving it in a text file.
Problem
hh:mm a is the format in which i am taking input form user. If i enter 12:30 PM, it is saved in text file with current date as 2019-03-20T12:30 without indication of AM or PM.
Consequently, when i read it from text file, i get the date-time information without AM or PM.
Question
Why is AM or PM not saved in the text file and how can i get it from LocalDateTime instance?
Code
Following method takes input from user, converts the user input in to LocalDateTime instance and returns it which is then saved to text file as a String
private static LocalDateTime getTimeInput(String question) {
System.out.print(question);
String userInput = scanner.nextLine();
userInput = AppointmentManager.validateTimeString(userInput, question);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd h:m a");
String todaysDateString = LocalDate.now().toString();
userInput = todaysDateString + " " + userInput;
return LocalDateTime.parse(userInput, formatter);
}
validateTimeString function is used to verify that user input is in correct format
Following method saves the data to text file
private static final File file = new File("appointments_data.txt");
public static void saveAppointmentInfo(Appointment appointment, boolean appendToFile) {
try (FileWriter fw = new FileWriter(file, appendToFile);
BufferedWriter bfw = new BufferedWriter(fw)) {
String str = AppointmentDataManager.getAppointmentInfoAsString(appointment);
bfw.write(str);
bfw.newLine();
} catch (IOException ex) {
ex.printStackTrace();
}
}
getAppointmentInfoAsString method
private static String getAppointmentInfoAsString(Appointment appointment) {
StringBuilder sb = new StringBuilder();
sb.append(appointment.getPatientId())
.append(";")
.append(appointment.getStartTime())
.append(";")
.append(appointment.getEndTime())
.append(";")
.append(appointment.getDoctor().getName());
return sb.toString();
}
When you are using StringBuilder you are calling LocalDateTime.toString() when the String segment is appended. As per LocalDateTime.toString() method javadoc:
The output will be one of the following ISO-8601 formats:
uuuu-MM-dd'T'HH:mm
uuuu-MM-dd'T'HH:mm:ss
uuuu-MM-dd'T'HH:mm:ss.SSS
uuuu-MM-dd'T'HH:mm:ss.SSSSSS
uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSS
You need to save LocalDateTime with custom format to get AM/PM:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd h:m a");
sb.append(appointment.getPatientId())
.append(";")
.append(appointment.getStartTime().format(formatter))
.append(";")
.append(appointment.getEndTime().format(formatter))
.append(";")
.append(appointment.getDoctor().getName());
Take a look at simple example of how to do it. Apply it accordignaly.
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("KK:mm:ss a", Locale.ENGLISH);
String now = LocalDateTime.now().format(formatter);
System.out.println(now);
}
This is only for Java 1.8 and later.
Sign Meaning Type Example
a Am/pm marker Text PM
K Hour in am/pm (0-11) Number 0

how to parse this date in java

please tell me how to parse this date: "29-July-2012"
I try:
new SimpleDateFormat("dd-MMM-yyyy");
but it doesn't works. I get the following exception:
java.text.ParseException: Unparseable date: "29-July-2012"
You need to mention the Locale as well...
Date date = new SimpleDateFormat("dd-MMMM-yyyy", Locale.ENGLISH).parse(string);
In your String, the full format is used for month, so according to http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html you should be using MMMM as suggested in Baz's comment.
The reason for this can be read from the API docs.
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html#month states that for month it will be interpreted as text if there are more than 3 characters and
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html#text states that the full form (in your case 'July' rather than 'Jul') will be used for 4 or more characters.
Try this (Added Locale.ENGLISH parameter and long format for month)
package net.orique.stackoverflow.question11815659;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class Question11815659 {
public static void main(String[] args) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMMM-yyyy",
Locale.ENGLISH);
System.out.println(sdf.parse("29-July-2012"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Use the split() function with the delimiter "-"
String s = "29-July-2012";
String[] arr = s.split("-");
int day = Integer.parseInt(arr[0]);
String month = arr[1];
int year = Integer.parseInt(arr[2]);
// Now do whatever u want with the day, month an year values....
Create a StringTokenizer. You first need to import the library:
import Java.util.StringTokenizer;
Basically, you need to create a delimeter, which is basically something to seperate the text. In this case, the delimeter is the "-" (the dash/minus).
Note: Since you showed the text with quotations and said parse, i'm assuming its a string.
Example:
//Create string
String input = "29-July-2012";
//Create string tokenizer with specified delimeter
StringTokenizer st = new StringTokenizer(input, "-");
//Pull data in order from string using the tokenizer
String day = st.nextToken();
String month = st.nextToken();
String year = st.nextToken();
//Convert to int
int d = Integer.parseInt(day);
int m = Integer.parseInt(month);
int y = Integer.parseInt(year);
//Continue program execution

Categories