i want to get arrival date of a client in string and pass it as a parameter to strToCal method,this method returns an Calendar object with that date,but it wouldn't work,id get parse exception error:
static String pattern = "yyyy-MM-dd HH:mm:ss";
System.out.println("enter arrival date ("+ pattern +"):\n" );
c.setArrDate(strToCal(sc.next(),c));
System.out.println("enter departure date ("+ pattern +"):\n");
c.setResTilDate(strToCal(sc.next(),c));
static Calendar strToCal(String s, Client c) throws ParseException {
try{
DateFormat df = new SimpleDateFormat(pattern);
Calendar cal = Calendar.getInstance();
cal.setTime(df.parse(s));
return cal;
} catch(ParseException e){
System.out.println("somethings wrong");
return null;
}
Replace sc.next() with sc.nextLine();
because sc.next() will split on the first space and your input string won't be of the correct pattern.
Edit I've tried this code:
public class Test4 {
static String pattern = "yyyy-MM-dd HH:mm:ss";
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
final Scanner input = new Scanner(System.in);
System.out.println("input date: ");
String a = input.nextLine();
c = strToCal(a);
System.out.println(c.getTime());
}
static Calendar strToCal(String s) {
try {
DateFormat df = new SimpleDateFormat(pattern);
Calendar cal = Calendar.getInstance();
cal.setTime(df.parse(s));
return cal;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
}
with next():
input date:
2014-05-16 13:30:00
java.text.ParseException: Unparseable date: "2014-05-16"
at java.text.DateFormat.parse(Unknown Source)
with nextLine():
input date:
2014-05-16 13:30:00
Fri May 16 13:30:00 EEST 2014
Related
I have this Date in a String with a 2 digit year.
I need to convert in another format. I tried with SampleDateFormat but it didn't work.
The SampleDateFormat is giving wrong format i.2 date with UTC and timestamp
I want in yyyy/MM/dd only.
Is there any other way to do this?
String receiveDate = "7/20/21";
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
try {
rdate = sdf.parse(receiveDate);
} catch (ParseException e) {
e.printStackTrace();
}
String recievedt = rdate.toString();
String dateParts[] = recievedt.split("/");
// Getting day, month, and year from receive date
String month = dateParts[0];
String day = dateParts[1];
String year = dateParts[2];
int iday = Integer.parseInt(day);
int imonth = Integer.parseInt(month);
int iyear = Integer.parseInt(year);
LocalDate date4 = LocalDate.of(iyear, imonth, iday).plusDays(2*dueoffset);
If you can use the java.time API I would suggest something along the lines of the following:
String input = "7/20/21";
LocalDate receivedDate = LocalDate.parse(input, DateTimeFormatter.ofPattern("M/dd/yy"));
String formatted = receivedDate.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
// or if you actually need the date components
int year = receivedDate.getYear();
...
How is String receiveDate="7/20/21"; a valid date?
String dateStr = "07/10/21";
SimpleDateFormat receivedFormat = new SimpleDateFormat("yy/MM/dd");
SimpleDateFormat finalFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = receivedFormat.parse(dateStr);
System.out.println(finalFormat.format(date)); // 2007/10/21
This, however, requires that you have date with leading zeros for year, month and date. If that is not the case, please sanitize your date string.
public static String sanitizeDateStr(String dateStr) {
String dateStrArr[] = dateStr.split("/");
String yearStr = String.format("%02d", Integer.parseInt(dateStrArr[0]));
String monthStr = String.format("%02d", Integer.parseInt(dateStrArr[1]));
String dayStr = String.format("%02d", Integer.parseInt(dateStrArr[2]));
return String.format("%s/%s/%s", yearStr, monthStr, dayStr);
}
public static void main (String[] args) throws Exception {
String dateStr = sanitizeDateStr("7/10/21");
SimpleDateFormat receivedFormat = new SimpleDateFormat("yy/MM/dd");
SimpleDateFormat finalFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = receivedFormat.parse(dateStr);
System.out.println(finalFormat.format(date));
}
I'm using the code below to check if an hour is between two other specific hours:
String openHour = "08:00 AM";
String currentHour = "10:00 PM";
String closeHour = "11:00 PM"; //Change to 02:00 AM doesn't work!!!
SimpleDateFormat format = new SimpleDateFormat("hh:mm a");
Date openHourDate = format.parse(openHour);
Date currentHourDate = format.parse(currentHour);
Date closeHourDate = format.parse(closeHour);
Calendar openCalendar = Calendar.getInstance();
openCalendar.setTime(openHourDate);
Calendar currentCalendar = Calendar.getInstance();
currentCalendar.setTime(currentHourDate);
Calendar closeCalendar = Calendar.getInstance();
closeCalendar.setTime(closeHourDate);
Date open = openCalendar.getTime();
Date current = currentCalendar.getTime();
Date close = closeCalendar.getTime();
if (current.after(open) && current.before(close)) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect!");
}
If the currentHour is "10:00 PM" as you see in my code, everything works fine but if I change the change it to "02:00 AM", the code doesn't work as expected even if the currentHour is between 08:00 AM and 02:00 AM. How to solve this?
Here is a solution using LocalTime that also correctly handles current and closing time being after midnight.
String openHour = "08:00 AM";
String currentHour = "01:00 PM";
String closeHour = "02:00 AM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "hh:mm a" , Locale.US );
LocalTime openTime = LocalTime.parse(openHour, formatter);
LocalTime currentTime = LocalTime.parse(currentHour, formatter);
LocalTime closeTime = LocalTime.parse(closeHour, formatter);
boolean isOpen = false;
if (closeTime.isAfter(openTime)) {
if (openTime.isBefore(currentTime) && closeTime.isAfter(currentTime)) {
isOpen = true;
}
} else if (currentTime.isAfter(openTime) || currentTime.isBefore(closeTime)) {
isOpen = true;
}
if (isOpen) {
System.out.println("We are open");
} else {
System.out.println("We are closed");
}
Just need to roll the day, as Michael Platt suggested:
import java.util.*;
import java.text.*;
public class Foo {
public static void main(String[] args) throws Exception {
String openHour = "08:00 AM";
String currentHour = "10:00 PM";
String closeHour = "11:00 PM"; //Change to 02:00 AM doesn't work!!!
SimpleDateFormat format = new SimpleDateFormat("hh:mm a");
Date openHourDate = format.parse(openHour);
Date currentHourDate = format.parse(currentHour);
Date closeHourDate = format.parse(closeHour);
Calendar openCalendar = Calendar.getInstance();
openCalendar.setTime(openHourDate);
Calendar currentCalendar = Calendar.getInstance();
currentCalendar.setTime(currentHourDate);
Calendar closeCalendar = Calendar.getInstance();
closeCalendar.setTime(closeHourDate);
if (closeCalendar.before(openCalendar)) {
closeCalendar.add(Calendar.DAY_OF_YEAR, 1);
}
Date open = openCalendar.getTime();
Date current = currentCalendar.getTime();
Date close = closeCalendar.getTime();
if (current.after(open) && current.before(close)) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect!");
}
}
}
this programe should subtract 2 days tare3 and tare4 . tare3 valued from current day (from system ) tare4 value from text file (element [3]) , when i parsed string (element[3]) to date (tare4) its give`me parseexception
date saved in file looked like (Thu Jan 24 00:00:00 EET 2018)
package javaapplication3;
import java.io.*; ` `
import java.util.*;
import java.text.*;
public static void main(String[] args) throws ParseException, FileNotFoundException {
private static String tare5 = new String();
static String tare2 = new String ();
DateFormat dateFormat = new SimpleDateFormat(" dd MMM yyyy ",Locale.ENGLISH );
Calendar cal = Calendar.getInstance();
Date tare4 = new Date ();
tare5 = dateFormat.format(cal.getTime());
Date tare3 = dateFormat.parse(tare5);
Scanner scanner;
File Myfile = new File("C:\\Users\\mido\\Documents\\NetBeansProjects\\JavaApplication3\\src\\javaapplication3\\products.txt");
scanner = new Scanner (Myfile);
while (scanner.hasNext()){
String line = scanner.nextLine();
StringTokenizer x = new StringTokenizer(line,"~");
String [] element= new String [7];
int counter = 0 ;
while (x.hasMoreElements())
{
element[counter]=(String)x.nextElement();
counter ++;
}
tare4 = dateFormat.parse(element[3]);
if (tare4.getTime()>= tare3.getTime() )
{
System.out.println(element[1]+"is expired");
}
else {
long def = tare3.getTime()- tare4.getTime();
System.out.println(element[1]+"has"+def+"to expire");}
}
}
The stacktrace is as :
Exception in thread "main" java.text.ParseException: Unparseable date: "20/10/2015 " at java.text.DateFormat.parse(DateFormat.java:357) at javaapplication3.JavaApplication3.main(JavaApplication3.java:51)
Your input 20/10/2015 doesn't meet the cases to fall under the dateFormat. You might want to change
SimpleDateFormat(" dd MMM yyyy ",Locale.ENGLISH )
to
SimpleDateFormat("dd/MM/yyyy",Locale.ENGLISH )
I would like to compare a Date I get from my local machine to an integer I get from a scanner. The date is formated as: MMDDYYYY such as 11232015 which is todays date. My integer is then 11192015. I want to convert my date to an integer and then compare the true date vs. the one I got from my scanner:
Calendar c;
DateFormat df = new SimpleDateFormat("MMddyyyy");
c.getInstance();
Date currentDate = c.getTime();
int dateFromScanner = 11192015;
Date formattedDate = df.format(currentDate);
if (dateFromScanner !> formattedDate {
// Do some stuff
} else {
System.out.println("This date has not yet passed.");
}
But I cannot compare dates to integers.
You can do something like that:
DateFormat df = new SimpleDateFormat("MMddyyyy");
Date currentDate = new Date();
int dateFromScanner = 11192015;
try {
Date formattedDateFromScanner = df
.parse(String.valueOf(dateFromScanner));
if (formattedDateFromScanner.before(currentDate)) {
// Do some stuff
} else {
System.out.println("This date has not yet passed.");
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try a solution like this, it can give you some idea what do you do.
public static void main(String[] args) {
Calendar c = null;
Scanner sc = new Scanner(System.in);
System.out.println("Enter date value like yyyyMMdd.");
int dat = sc.nextInt();
DateFormat df = new SimpleDateFormat("yyyyMMdd");
Date currentDate = c.getInstance().getTime();
String formattedDate = df.format(currentDate);
System.out.println(formattedDate);
if (dat < Integer.parseInt(formattedDate)) {
System.out.println("This date had being passed.");
} else {
System.out.println("This date has not yet passed.");
}
}
In my code I want to have the individual numbers from date format so I can use them as int values:
public static final String DATE_FORMAT = "dd.MM.yyyy";
public int age()
{
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
Date date = new Date();
// How to convert to int?
int currentnDay = ?;
int currentMonth = ?;
int currentYear = ?;
}
also I would like some user input to define day,month and year in one go, if that's even possible:
private Date dateOfPublication;
public void input()
{
Scanner scn = new Scanner( System.in );
System.out.print( "Please enter dateOfPublication: " );
// How to setup input for this?
}
I hope you can help me out, previously I did it all seperatly but the code was quite big and I think it would be prettier if I could do it like that..
update: okay I'm doing the input like this now:
System.out.print( "Please enter dateOfPublication, use format of x.x.xxxx: " );
userInputDate = scn.next();
String[] ary = userInputDate.split("\\.");
publicationDay = Integer.parseInt(ary[0]);
publicationMonth = Integer.parseInt(ary[1]);
publicationYear = Integer.parseInt(ary[2]);
thanks for your help!
Take a look at Java 8's new Time API (or JodaTime or Calendar if you're really stuck)
LocalDate ld = LocalDate.parse("16.10.2015", DateTimeFormatter.ofPattern(DATE_FORMAT));
System.out.println(ld);
System.out.println(ld.getDayOfMonth());
System.out.println(ld.getMonth().getValue());
System.out.println(ld.getYear());
Which outputs
2015-10-16
16
10
2015
Now, you could simply ask the user to input a date in a given format and try and parse the result, if the parsing fails, you could reprompt them
For example...
Scanner input = new Scanner(System.in);
LocalDate ld = null;
do {
System.out.print("Please enter date in " + DATE_FORMAT + " format: ");
String value = input.nextLine();
try {
ld = LocalDate.parse(value, DateTimeFormatter.ofPattern(DATE_FORMAT));
} catch (Exception e) {
System.err.println(value + " is not a valid date for the format of " + DATE_FORMAT);
}
} while (ld == null);
System.out.println(ld);
System.out.println(ld.getDayOfMonth());
System.out.println(ld.getMonth().getValue()); // Is probably 0 indexed
System.out.println(ld.getYear());
You can use:
dateFormat.format(today).split("\\.");
For your code:
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
Date date = new Date();
String[] dateArr = dateFormat.format(today).split("\\.");
int currentnDay = Integer.parseInt(dateArr[0]);
int currentMonth = Integer.parseInt(dateArr[1]);
int currentYear = Integer.parseInt(dateArr[2]);
IdeOne Example
First, you have to parse the input string
The Calendar data type is more flexible for date-time handling. This is an example that shows some Date/Calendar operations.
Date date;
Calendar c;
// Get the current date
c = Calendar.getInstance();
System.out.println("Current Calendar:" + c.getTime().toString());
int currentnDay = c.get(Calendar.DATE);
int currentMonth = c.get(Calendar.MONTH);
int currentYear = c.get(Calendar.YEAR);
System.out.println(String.format("Current Values: %d/%d/%d",
currentnDay, currentMonth, currentYear));
String DATE_FORMAT = "dd.MM.yyyy";
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
date = dateFormat.parse("11.10.1981");
System.out.println("Modified Date:" + date.toString());
// reset Calendar
c = Calendar.getInstance();
// set date to the calendar
c.setTimeInMillis(date.getTime());
currentnDay = c.get(Calendar.DATE);
currentMonth = c.get(Calendar.MONTH);
currentYear = c.get(Calendar.YEAR);
System.out.println(String.format("Modified Values: %d/%d/%d",
currentnDay, currentMonth, currentYear));
This is the output of the example.
Current Calendar:Thu Oct 15 20:22:59 EDT 2015
Current Values: 15/9/2015
Modified Date:Sun Oct 11 00:00:00 EDT 1981
Modified Values: 11/9/1981