how to comparison between two date in android? - android

I want to Date comparison between Start Date and End Date. End Date is Greater than Start Date OR End Date is Equal to Start Date. How to possible? Its Comparison between only day. If I am enter Start Date is "15-12-2014" and End Date is "14-07-2015" then Its Not Accept. What is my Mistake? Please Guide me.
Thanks in Advance.
boolean b=false;
public boolean isDateAfter(String startDate, String endDate) {
try {
SimpleDateFormat sdf;
String myFormatString = "dd-mm-yyyy"; // for example
sdf = new SimpleDateFormat(myFormatString);
endingDate = sdf.parse(endDate);
startingDate = sdf.parse(startDate);
System.out.println("!!!!!!!!!! startingDate===="+startingDate);
System.out.println("!!!!!!!!!!! endingDate====="+endingDate);
if ((endingDate.after(startingDate))
|| (endingDate.equals(startingDate)))
b = true;
else
b = false;
} catch (Exception e) {
b = false;
}
return b;
}

Dont use SimpleDateFormat, use Time stamp like:
Long tsLong = System.currentTimeMillis() / 1000;

you can use the built in methods date.after,date.before and date.equals to do this easily

You may rely on the built-in methods like date.after() or date.before() for comparison.
For more control, you may also convert your date into long value by using date.getTime() and perform further calculations.

Related

Why my unit test fails altough method works good?

I try to count time interval. I parse String date into Date object for some pattern.
public static float countTimeAgo(String timestamp){
// date pattern
SimpleDateFormat simpleDateFormat
= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
simpleDateFormat.setLenient(false);
// time interval
float diff;
try {
// convert timestamp to given pattern
Date timestampDate = simpleDateFormat.parse(timestamp);
// get actual date and convert to pattern
Date date = new Date();
simpleDateFormat.format(date);
// count difference in millis
diff = date.getTime() - timestampDate.getTime();
// convert millis to minutes
diff = diff/(1000*60);
} catch (ParseException e) {
return -1;
}
if (diff < 0)
return -1;
else
return diff;
}
When I put string "2018-03-08 23:28:07.807353" as argument while running my app, method is returning non -1 value. But when I run a test, it fails:
#Test
public void testCountTimeAgo(){
String date = "2018-03-08 23:28:07.807353";
assertTrue(PostTimeProvider.countTimeAgo(date) != -1);
}
AssertionError:
java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:86)
at org.junit.Assert.assertTrue(Assert.java:41)
at org.junit.Assert.assertTrue(Assert.java:52)
Does somebody knows why?
In your code -1 can be returned when the parsing fails or if the date was in future. You should check which one is happening in this case. Perhaps your device and the device running the unit tests have different time?

Does a given time fall into a given time interval in android?

I have a time interval - 12:00 PM to 11:59 PM.
When the user enters the time as "06:15 PM", check against that interval.
If the time falls into that interval, return true else return false.
I searched for thisin Google, but I didn't get the correct solution.
Can anyone help me to solve this issue?
String From = "12:00 PM";
String to = "11:59 PM";
String user_given_input = "06:15 PM";
You could parse it into a Date object using a SimpleDateFormatter.
After you've done that you can use fromDate.before(user_given_input_date) && toDate.after(user_given_input_date).
assuming fromDate, toDate & user_given_input_date are Date objects
Try this code, it should work.
static boolean checkTimeInterval(String s) {
String From = "12:00 PM";
String to = "11:59 PM";
SimpleDateFormat d = new SimpleDateFormat("hh:mm a");
boolean isLie = false;
try {
Date from = d.parse(From);
Date too = d.parse(to);
Date input = d.parse(s);
if (input.before(too) && input.after(from)) {
isLie = true;
}
} catch (ParseException e) {
System.out.println("Check input string format");
e.printStackTrace();
}
return isLie;
}
You may call this function as
checkTimeInterval("06:15 PM")

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 .

SimpleDateFormat get only the time

I have a problem when I try to get only the time from a Timestamp.
An example of the Timestamp is:
2012-04-19T23:05:00+0200
I think the format is "yyyy-MM-dd'T'HH:mm:ss.SSSZ" right?
And it must be "HH:mm".
I use the following code, but it returnes nothing:
public String getTime(String Vertrektijd){
final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date dateObj;
String newDateStr = null;
try
{
dateObj = df.parse(Vertrektijd);
SimpleDateFormat fd = new SimpleDateFormat("HH:mm");
newDateStr = fd.format(dateObj);
}
catch (Exception e)
{
e.printStackTrace();
}
return newDateStr;
}
Thanks for the help!
Your code is correct...
In the example time what you have given in the question(ie, "2012-04-19T23:05:00+0200") is missing MilliSeconds
Try passing this
getTime("2012-04-19T23:05:00.235+0200");
It should work.
Edit:
As MH mentioned, If you dont want to use milliseconds
you can change the code to
final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date has a getHours() and getMinutes() function, but it is deprecated. The proper way would be to use a Calendar
Calendar calendar = Calendar.getInstance();
calendar.setTime( dateObj );
int hours = calendar.get( Calendar.HOUR_OF_DAY );
int minutes = calendar.get( Calendar.MINUTE );
Here is an attempt to summarize all the confusing classes that Java and Android provide to do with dates, times and timezones. Basically, you do most of your date/time manipulations using GregorianCalendar objects, probably using methods from the Calendar superclass. To do locale-specific formatting, you need a DateFormat. But that can only format Date objects, so you need to convert your Calendar/GregorianCalendar to one of those first. Basically, SimpleDateFormat is for doing custom formatting, as you’ve already discovered.
Note there are two different classes called “DateFormat”.

Categories

Resources