Java day of the week from string - java

I have this simple code:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse("2011-10-29");
calendar.setTime(date);
Log.d("Debug","Day of the week = "+(calendar.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY));
The 29th of October is a Saturday so why do I get false?

Here is an example of how this could happen...
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse("2011-10-29");
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.setTime(date);
System.out.println("Day of the week = "
+ (calendar.get(Calendar.DAY_OF_WEEK)));
System.out.println("Saturday? "
+ (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY));
try {
date = format.parse("2011-10-29");
} catch (ParseException e) {
e.printStackTrace();
}
calendar = Calendar.getInstance(TimeZone.getTimeZone("PST"));
calendar.setTime(date);
System.out.println("Day of the week = "
+ (calendar.get(Calendar.DAY_OF_WEEK)));
System.out.println("Saturday? "
+ (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY));
which outputs
Day of the week = 7
Saturday? true
Day of the week = 6
Saturday? false
so yes, depending on what time zone you are in it will or will not be Saturday.

Getting true with the following code:
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse("2011-10-29");
Calendar cal = GregorianCalendar.getInstance();
cal.setTime(date);
System.out.println(cal.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY);
}
catch(Exception e) {
e.printStackTrace();
}
Maybe a locale setting?

Related

Getting incorrect result when checking a date between two other dates in Java

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

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.

"java.text.ParseException: Unparseable date" thrown for time text

Hi I am Calling below function to find time elapsed, till that date, It is working fine for all but following input : 12:46:21 PM
public Long timeDifference(String weboutput) {
try {
Calendar calendar = GregorianCalendar.getInstance();
Calendar today = new GregorianCalendar();
Date inputTime;
if (weboutput.length() <= 10) { // for data fetched for current date.
DateFormat formatter = new SimpleDateFormat("hh:mm:ss a", Locale.US);
inputTime = formatter.parse(weboutput);
calendar.setTime(inputTime);
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
today.setTime(new Date());
today.set(Calendar.HOUR, hour);
today.set(Calendar.MINUTE, minute);
today.set(Calendar.SECOND, second);
} else {
if (weboutput.length() <= 15) { // for data for earlier date in same year or month.
DateFormat formatter = new SimpleDateFormat("MMM dd hh:mm a", Locale.US);
inputTime = formatter.parse(weboutput);
calendar.setTime(inputTime);
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int month = calendar.get(Calendar.MONTH);
int date = calendar.get(Calendar.DATE);
today.setTime(new Date());
today.set(Calendar.HOUR, hour);
today.set(Calendar.MINUTE, minute);
today.set(Calendar.MONTH, month);
today.set(Calendar.DATE, date);
} else { // for data with different year.
DateFormat formatter = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a", Locale.US);
inputTime = formatter.parse(weboutput);
calendar.setTime(inputTime);
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
int month = calendar.get(Calendar.MONTH);
int date = calendar.get(Calendar.DATE);
int year = calendar.get(Calendar.YEAR);
today.setTime(new Date());
today.set(Calendar.HOUR, hour);
today.set(Calendar.MINUTE, minute);
today.set(Calendar.SECOND, second);
today.set(Calendar.YEAR, year);
today.set(Calendar.MONTH, month);
today.set(Calendar.DATE, date);
}
}
Date retrivedDate = today.getTime();
Calendar cal = Calendar.getInstance();
Date currentDate = cal.getTime();
difference = currentDate.getTime() - retrivedDate.getTime();
System.out.println(retrivedDate);
System.out.println(currentDate);
System.out.println(difference);
} catch (ParseException e) {
e.printStackTrace();
}
return difference;
}
public boolean alarmValue(Long alarmTime) {
if (alarmTime <= 1800000) // change this value for Alarm duration, currently 30 min = 30* 60 s = 1800 * 1000 ms = 1800000 ms.
return false;
else
return true;
}
the error is as follows:
java.text.ParseException: Unparseable date: "12:46:21 PM"
at java.text.DateFormat.parse(DateFormat.java:357)
at rcm.Selenium.Test.Calculations.timeDifference(Calculations.java:29)
at rcm.Selenium.Test.RcmSeleniumTest.main(RcmSeleniumTest.java:89)
Exception in thread "main" java.lang.NullPointerException
at rcm.Selenium.Test.Calculations.alarmValue(Calculations.java:76)
at rcm.Selenium.Test.RcmSeleniumTest.main(RcmSeleniumTest.java:90)
Kindly help me with this.
"12:46:21 PM" has 11 digits and therefore doesn't pass your first test (which is for <= 10 digits) for the format "hh:mm:ss a".

Date Format Java?

I have 3 int variables for Month, Day and Year.
How can I convert them to a java.util.Date object (or whatever).
For Example, Month = 12, Date = 20, Year = 2011
It should be print in medium date format: **Dec 20, 2011**
Thank you very much!
Edit here my try:
String yourBirthDay = Integer.toString(birthMonth) + "." + Integer.toString(birthDay) + "." + Integer.toString(birthYear);
DateFormat format = DateFormat.getDateInstance(DateFormat.SHORT);
try {
Date date = format.parse(yourBirthDay);
System.out.println("Your birth date is : " + date.toString());
} catch (ParseException pe) {
System.out.println("ERROR: could not parse date in string \""
+ yourBirthDay + "\"");
}
I did this little test using Calendar.set(int year,int month, int date):
#Test
public void testDate() throws ParseException {
int year = 2011, month = 12, date = 20;
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, date);
Date javaDate = calendar.getTime();
// SimpleDateFormat format = new SimpleDateFormat("MMM dd, yyyy");
DateFormat format = DateFormat.getDateInstance(DateFormat.MEDIUM);
String stringDate = format.format(javaDate);
assertEquals("Dec 20, 2011", stringDate);
}
You need to remove 1 from the month because java.util.Calendar works with zero based months.

How to find previous date if current date is given as a String?

How to find previous date if current date is given as a String? Below is given my code. Is there any shorter solution?
private static String previousDay(String date) {
String[] ymd = date.split("-");
int year = Integer.parseInt(ymd[0]);
int month = Integer.parseInt(ymd[1]);
int day = Integer.parseInt(ymd[2]);
String newDate = "";
if (day > 1 & month > 1)
newDate = year+"-"+month+"-"+(day-1);
else if (day == 1 & month > 1) {
Calendar calendar = new GregorianCalendar(year,month-1, 1);
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
newDate = year+"-"+(month-1)+"-"+daysInMonth;
} else if (day == 1 & month == 1) {
Calendar calendar = new GregorianCalendar(year,12, 1);
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
newDate = year+"-"+12+"-"+daysInMonth;
}
return newDate;
}
You need to convert your String to Date, in order to do date calculations. You can use Calender to find previous day. From your code, I assume, your date format is yyyy-MM-dd.
String input = "2009-09-30";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date myDate = dateFormat.parse(input);
Calendar cal1 = Calendar.getInstance();
cal1.setTime(myDate);
cal1.add(Calendar.DAY_OF_YEAR, -1);
Date previousDate = cal1.getTime();
Date currentDate= new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(currentDate);
calendar.add(Calendar.DAY_OF_YEAR, -1);
Date previousDate = calendar.getTime();
// dccTimeStamp is "20120122121212"
String dccTimeStamp is "20120122121212"
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date dcc = sdf.parse(dccTimeStamp);
log.debug("Dcc Date is " + dcc.toString());
From this point on you can use Date (or Calendar) utilities and perform the Date operation you need.

Categories