Compare formatted dates to integers in Java - java

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

Related

Change date format from m/dd/yy to yyyy/MM/dd in Java

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

How can I use updated value of date1 in 2nd if block. showing error "date1 cannot be resolved"

public class test {
public static void check1 (String date) throws ParseException {
SimpleDateFormat sdf1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("MMMM dd, yyyy");
if(date.matches("^\\w+.+")) {
Date date1 = sdf2.parse(date);
}
else {
Date date1 = sdf1.parse(date);
}
Date current = new Date();
if(date1.compareTo(current)<-1) {
System.out.println("In Past");
}
else {
System.out.println("Same or future date");
}
How can I use the updated value of date1 in second if block.
A variable is only visible within the scope it is declared (between it's enclosing { and } ).
Your 2 date1 variables are declared (Date date1) within the scope of the if and the else blocks. Therefore they are not visible outside (they effectively don't exist outside of those scopes).
You need to declare it outside:
public static void check1(String date) throws ParseException {
SimpleDateFormat sdf1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("MMMM dd, yyyy");
Date date1; // <- declare date1 here
if (date.matches("^\\w+.+")) {
date1 = sdf2.parse(date);
} else {
date1 = sdf1.parse(date);
}
Date current = new Date();
if (date1.compareTo(current) < -1) {
System.out.println("In Past");
} else {
System.out.println("Same or future date");
}
}
You have declared your variable in a scope, which is ending when you close your bracket, aka it is no longer alive after that. What you could do is you can take it out:
public static void check1 (String date) throws ParseException {
SimpleDateFormat sdf1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("MMMM dd, yyyy");
Date date1;
if(date.matches("^\\w+.+")) {
date1 = sdf2.parse(date);
}
else {
date1 = sdf1.parse(date);
}
Date current = new Date();
if(date1.compareTo(current)<-1) {
System.out.println("In Past");
}
else {
System.out.println("Same or future date");
}
}

Check if a given time-stamp lies between two time-stamp in android

I want to check if a given time-stamp lies between two time-stamp
Below is my code:
public static boolean isTimeBetweenTwoTime(String initialTime, String finalTime, String currentTime) throws ParseException {
String reg = "^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$";
if (initialTime.matches(reg) && finalTime.matches(reg) && currentTime.matches(reg)) {
boolean valid = false;
//Start Time
java.util.Date inTime = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(initialTime);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(inTime);
//Current Time
java.util.Date checkTime = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(currentTime);
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(checkTime);
//End Time
java.util.Date finTime = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(finalTime);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(finTime);
if (finalTime.compareTo(initialTime) < 0) {
calendar2.add(Calendar.DATE, 1);
calendar3.add(Calendar.DATE, 1);
}
java.util.Date actualTime = calendar3.getTime();
if ((actualTime.after(calendar1.getTime()) || actualTime.compareTo(calendar1.getTime()) == 0)&& actualTime.before(calendar2.getTime())) {
valid = true;
}
return valid;
} else {
throw new IllegalArgumentException("Not a valid time, expecting MM/dd/yyyy HH:mm:ss format");
}
}
But Its not working for me, Please Help
Try this simple logic:
long mills = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date resultdate = new Date(mills);
String currentTime = sdf.format(resultdate);
System.out.println(sdf.format(resultdate));
try{
java.util.Date inTime1 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(initialTime);
java.util.Date inTime2 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(finalTime);
java.util.Date inTime3 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(currentTime);
if (inTime3.getTime() > inTime1.getTime() && inTime3.getTime() < inTime2.getTime()){
Log.e("TimeDifference","inTime3 is between inTime1 and inTime2");
return true;
}else{
Log.e("TimeDifference","in Else Condition");
return false;
}
}catch (Exception e){
e.printStackTrace();
return false;
}
Please tell if you have any issue.

How to Compare datetime in Android

I have dates, date1(now) and date2 which is returned in a JSON string say 2016-07-09 21:26:04.
I want to compare those two dates something like
if(date1 < date2){
}
Here is the code to compare two DateTime objects in Android:
public void onDateSelected(DateTime dateSelected) {
DateTime currentDateTime = new DateTime();
try{
// You can use any format to compare by spliting the dateTime
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ");
String str1 = dateSelected.toString();
Date selectedDate = formatter.parse(str1);
String str2 = currentDateTime.toString();
Date currentDate = formatter.parse(str2);
if (selectedDate.compareTo(currentDate)<0)
{
System.out.println("current date is Greater than my selected date");
}
else
{
System.out.println("selected date is Greater than my current date");
}
}catch (ParseException e1){
e1.printStackTrace();
}
}
I would do this:
parse the in to Date objects
compare those
Example:
public static void main(String x[]) throws ParseException {
String s1 = "2016-07-09 21:26:04";
String s2 = "2006-07-09 21:26:04";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d1 = sdf.parse(s1);
Date d2 = sdf.parse(s2);
int compareResult = d1.compareTo(d2);
if (compareResult > 0) {
System.out.println(s1 + " is younger than " + s2);
} else if (compareResult < 0) {
System.out.println(s1 + " is younger than " + s2);
} else {
System.out.println(s1 + " is equals than " + s2);
}
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date today= new Date();
try {
if (today.before(sdf.forrmat(json_string_date))) {
// If start date is before end date.
// Do your piece of code
}
}catch (ParseException e) {
e.printStackTrace();
}

error in converting String to Calendar?

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

Categories