How to compare time ranges? - android

Hi i am trying to compare time ranges,My requirement is when i select time from time-picker dialog it should be under given time ranges for this i wrote below code this is working when i not select 12 or 00 from time picker dialog
start time:06:00
end time:23:00
selected time from time picker dialog:12:23
above timing not suitable for below code can some one help me please
String pattern = "hh:mm";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date date1 = sdf.parse(startTime);
Date date2 = sdf.parse(endTime);
Date date3 = sdf.parse(selectedTime);
if (((date3.after(date1) || date3.equals(date1)) && (date3.before(date2) || date3.equals(date2)))) {
}
else {
Toast.makeText(context, "Pickup time should be open and close timings", Toast.LENGTH_SHORT).show();
}

You can use code below .
String pattern = "HH:mm";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try {
Date date1 = sdf.parse(startTime);
Date date2 = sdf.parse(endTime);
Date date3 = sdf.parse(selectedTime);
if (date3.compareTo(date1) >= 0 && date3.compareTo(date2) <= 0) {
// Do your stuff
} else {
// Wrong time
}
} catch (Exception e) {
e.printStackTrace();
}
h represents Hour in am/pm (1-12)
H represents Hour in day (0-23)
Your date is in 24 hour formate so you should use H instead of h.

You should use compareTo().
CompareTo method must return negative number if current object is less
than other object, positive number if current object is greater than
other object and zero if both objects are equal to each other.
Code Reference
if (date1.compareTo(date2) < 0)
{
Log.d("RESULT","date1 older than date2");
}
else
{
Log.d("RESULT","date2 older than date1");
}
NOTE
Make sure your TIME format is perfect.

Related

how can i repeat my date format showing in listview as today,yesterday,tue,mon,sun,...wed,

how can i display my listview with the following date formats like if its today date show only time , and yesterday ,and tue,mon,sun,sat,fri,thu,wed and agian started with time , ysterday, tue......etc ?
i tried with this code but i'm not getting
if(Constant.hours-Constant.hours1 <= 23){
holder.txtTime.setText(newDateString);
}else if(Constant.hours-Constant.hours1 >= 23 && Constant.hours-Constant.hours1 <= 47){
holder.txtTime.setText("Yesterday");
}else if(Constant.days >= 2 && Constant.days<=2){
holder.txtTime.setText(Constant.strLong+" days ago");
}
Try this one...
//suppose your date time format is "12-08-2017" of variable newDateString then date format will be like SimpleDateFormat formatter = SimpleDateFormat .forPattern("dd-MM-yyyy");//
String newDateString="08/02/2017 18:41:11";
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
//SimpleDateFormat formatter = new SimpleDateFormat("your farmat here");
Date yourDate= null;
Date current= null;
Calendar cal = Calendar.getInstance();
try {
yourDate= formatter .parse(newDateString);//newDateString is your variable
current= formatter .parse(formatter.format(cal.getTime()));
} catch (java.text.ParseException e) {
e.printStackTrace();
}
int daysDiff= (int) ((yourDate.getTime() - current.getTime())/ (1000 * 60 * 60 * 24));
if(daysDiff< 1){
holder.txtTime.setText(newDateString);
}else if(daysDiff== 1){
holder.txtTime.setText("Yesterday");
}else if(daysDiff> 1){
holder.txtTime.setText(daysDiff+" days ago");
}
}else if(daysDiff<0){
holder.txtTime.setText(daysDiff+" days before");
}

Date and Date format Calculation Android

I have a function with date calculations. It compares the database from and to date which I already retrieved, with the input from and to date which I am passing. While debugging, it showing wrong dates after assignment inside the for loop.(input and database dates) Below I shown the example with a image.
Function code:
/*String[] veh - vehicle name, String[] from - table from date array,
* String[] to - table to date array,String from1 - input from date, String to1 - input to date*/
private List getDateComparison(String[] veh, String[] from, String[] to,String from1, String to1) throws ParseException {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:MM",Locale.ENGLISH);
Date table_from,table_to,input_from,input_to;
long diff=0,diff1=0,diff2=0,diff3=0;
int count=0,county=0;;
for(int i=0;i<veh.length;i++){
table_from=df.parse(from[i]);
table_to=df.parse(to[i]);
input_from=df.parse(from1);
input_to=df.parse(to1);
table_from=df.parse(df.format(table_from));
table_to=df.parse(df.format(table_to));
input_from=df.parse(df.format(input_from));
input_to=df.parse(df.format(input_to));
diff=table_from.getTime()-input_from.getTime();
diff1=table_from.getTime()-input_to.getTime();
diff2=input_from.getTime()-table_to.getTime();
diff3=input_to.getTime()-table_to.getTime();
if((diff > 0 && diff1>0) || (diff2 > 0 && diff3>0)){
count++;
removeAndAddList(veh[i],1);
Log.d("Date", " ok with from");
}
else {
county = 100;
removeAndAddList(veh[i],2);
}
}
return vehic;//= veh[0];
}
Function Screenshot while Debugging:
Edited:
Before I used the date format as,
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
At that time the calculation worked perfectly. Now it was making some issues with the date format. I think my dateformat is doing something wrong inside the for loop. It was showing bigger dates after assigning the dates with dateformat. Where I did wrong?
The format you are using for the SDF is not correct
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:MM",Locale.ENGLISH);
as M means Month in year and you are using it as minutes.
change to HH:mm
... = new SimpleDateFormat("yyyy-MM-dd HH:mm",Locale.ENGLISH);
off-topic:
instead of using diff=table_from.getTime()-input_from.getTime(); you can make use of after() and before() methods for Date
you can compare dates as following (from your code):
if((diff > 0 && diff1>0) || (diff2 > 0 && diff3>0)){
will be:
if((table_from.after(input_from) && table_from.after(input_to))
|| (input_from.after(table_to) && input_to.after(table_to))){
now you can remove all the getTime() subtraction lines from the code (the 4 lines)

Joda - Get the age from a birthday using a different format

I'm learning how to build Android applications, and I'm trying to get the age from my users, only using the birthday.
I'm already using Joda timer, but I'm getting the data from a Json file, and this Json file outputs the data like this:
1994-11-24 / YYYY-MM-d
I'm getting the json data inside a for loop, in Java.
//Variable
private static final String TAG_BIRTH_DATE = "birth_date";
...
//inside the Loop
String birth_date = c.getString(TAG_BIRTH_DATE);
My question is, how can I format the date, and get the age from the person?
I tried this, so far.
DateTimeFormatter formatter = DateTimeFormat.forPattern("d/MM/yyyy");
LocalDate date = formatter.parseLocalDate(birth_date);
LocalDate birthdate = new LocalDate (date);
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);
But is not working.
Thank you.
Try below method to calculate age of user and in parameter pass your date that you are getting from JSON
public static int getAge(String dateOfBirth) {
Calendar today = Calendar.getInstance();
Calendar birthDate = Calendar.getInstance();
int age = 0;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(dateOfBirth);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
birthDate.setTime(convertedDate);
if (birthDate.after(today)) {
throw new IllegalArgumentException("Can't be born in the future");
}
age = today.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR);
// If birth date is greater than todays date (after 2 days adjustment of
// leap year) then decrement age one year
if ((birthDate.get(Calendar.DAY_OF_YEAR)
- today.get(Calendar.DAY_OF_YEAR) > 3)
|| (birthDate.get(Calendar.MONTH) > today.get(Calendar.MONTH))) {
age--;
// If birth date and todays date are of same month and birth day of
// month is greater than todays day of month then decrement age
} else if ((birthDate.get(Calendar.MONTH) == today.get(Calendar.MONTH))
&& (birthDate.get(Calendar.DAY_OF_MONTH) > today
.get(Calendar.DAY_OF_MONTH))) {
age--;
}
return age;
}
You have just mismatched your pattern and then accepted an answer which uses minutes instead of months (small "m" versus big "M). The Joda-answer would be (pay attention to the different pattern please):
String birth_date = c.getString(TAG_BIRTH_DATE); // example: 1994-11-24
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-d");
LocalDate date = formatter.parseLocalDate(birth_date);
Years age = Years.yearsBetween(date, LocalDate.now());

How to Compare a Time with two other time provided?

Been confusing.. Like if we are comparing time, string is definitely not recommended... But if it is in the format of (HH:mm:ss). how should i compare them to do something?
For example:
Target1: 9:00:00
Target2: 23:00:00
how to do the logic for comparison where the input is larger than Target1 and smaller than Target2?
if(input > Target1 && input < Target2){
//do statement A
}else{
//do statement B
}
so if my input time is 10:00:00, it should run statement A
and if input time is 23:01:00, it should run statement B
how should i do that? is larger than (>) and smaller than (<) appropriate in time format?
Given them as string, you can convert them to a Date object from a SimpleDateFormat.
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
The easiest way is to convert them to the amount of milliseconds by doing
long time1 = sdf.parse(Target1).getTime();
long time2 = sdf.parse(Target2).getTime();
long inputTime = sdf.parse(input).getTime();
This way you are essentially doing a integer comparison, and you can forget about all the Date Time business.
if(inputTime > time1 && inputTime < time2)
SimpleDateFormat df=new SimpleDateFormat("hh:mm:ss");
Date d1=df.parse(dateToPars);
d1.after(otherTimeYouWantTocompare); OR
d1.before(otherTimeYouWantTocompare);
But you have to provide the time in the mentioned format
you can calculate diffrent using calender function .getTimeInMillis(), and get diffrent of 2 diffrent time , here you need to set only your specific time in Calender and make comparision with it
try{
Calendar calender = Calendar.getInstance();
Calendar calDb = Calendar.getInstance();
Calendar matchd = Calendar.getInstance();
mYear = calender.get(Calendar.YEAR);
mMonth = calender.get(Calendar.MONTH);
mDay = calender.get(Calendar.DAY_OF_MONTH);
mendYear = calDb.get(Calendar.YEAR);
mendMonth = calDb.get(Calendar.MONTH);
mendDay = calDb.get(Calendar.DAY_OF_MONTH);
// Here you can change day values
calDb.set(Calendar.DAY_OF_MONTH, mDay-1);
strbeforedate = mDateFormat.format(calDb.getTime());
curentdate = mDateFormat.format(calender.getTime());
calDb.setTime(mDateFormat.parse(strbeforedate));
calender.setTime(mDateFormat.parse(curentdate));
String mydate = "2013.03.14 03:11";
String mdatetime = "";
deletepath = new ArrayList<String>();
try{
// here your matching goes and pass date here
matchd.setTime(mDateFormat.parse(mdatetime));
long diff = calDb.getTimeInMillis() - calender.getTimeInMillis();
long matchdiff = matchd.getTimeInMillis() - calender.getTimeInMillis();
if(diff < matchdiff){
// do your work here
}else{
// do your else work here
}
}catch(Exception e){
e.printStackTrace();
}
}
}catch(Exception e){
e.printStackTrace();
}
}

How to convert current date and time format in milliseconds (only 10 digits)?

I have converted date format in milliseconds and time format in milliseconds. I am getting current time in more than 13 digits. CurrentTime= 1357755780000, StartingTime=1357602840, EndingTime=1357756140
But when I do comparison in below code, the if part is not executed, only the else part is executed.
Is there any mistake in my code? I want to make currentTime in 10 digits. So I think, conversion of date format to milliseconds is wrong.
String toParse = getDateorTime(1) + " " + getDateorTime(2);
long currentTime=0,startingTime=0,endingTime=0,milliseconds=0;
try
{
dateFormater = new SimpleDateFormat("yyyy/MMM/dd hh:mm");
Date date = null;
try {
date = dateFormater.parse(toParse);
date.setTime(milliseconds);
}catch (Exception e) {
System.out.println("\n Error in date parsing"+e.toString());
}
currentTime = (date.getTime());
start=Long.parseLong((cursor.getString(5).trim()));
end=Long.parseLong((cursor.getString(6).trim()));
}catch (ParseException pe) {
pe.printStackTrace();
}
if((currentTime>=startingTime)&&(currentTime<=endingTime))
{
//
}
Based on your examples, you actually have startingTime and endingTime in SECONDS, while you're comparing it to currentTime in MILLISECONDS. Simply multiply the second-times by 1,000, like so:
if((currentTime>=startingTime*1000L)&&(currentTime<=endingTime*1000L))
Simply divide by 1000
Calendar cal = Calendar.getInstance();
System.out.println(cal.getTimeInMillis()/1000);
Convert the long values to string and if length is >10 simply substring the value (0,10) and then you can use string .equals too or covert them back to long for comparison .

Categories

Resources