Check between two datetime if passed in Java/Android - java

I have two date time string, one is current time and second is given as follows.
String currentTime = "05/30/2018 16:56:21";
String endTime = "05/30/2018 16:59:21";
Now I want to check if the endTime has passed currentTime.
Thanks

Take a look at
this and this
Example:
String currentTime = "05/30/2018 16:56:21";
String endTime = "05/30/2018 16:59:21";
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyyHH:mm:ss");
try {
Date currentTimeDate = sdf.parse("05/30/2018 16:56:21");
Date endTimeDate = sdf.parse("05/30/2018 16:59:21");
currentTimeDate.compareTo(endTimeDate); // false / current time has not passed end time.
endTimeDate.compareTo(currentTimeDate); // true / end time has passed current time.
} catch (ParseException ignored) {
}

Convert both strings to Date object and then use before() method to check if the end time has passed currentTime.
String currentTime = "05/30/2018 16:56:21";
String endTime = "05/30/2018 16:59:21";
Date current=new SimpleDateFormat("dd/MM/yyyy").parse(currentTime);
Date end=new SimpleDateFormat("dd/MM/yyyy").parse(endTime);
if(end.before(current)) {
// end time has passed currenctTime
} else {
// no
}

Keep both times in milliseconds which is a long value
long currentTime= System.currentTimeMillis();
You can also convert your and time in millies using below code.
String givenDateString = "Tue Apr 23 16:08:28 GMT+05:30 2013";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
try {
Date mDate = sdf.parse(givenDateString);
long endTime= mDate.getTime();
System.out.println("Date in milli :: " + endTime);
} catch (ParseException e) {
e.printStackTrace();
}
Now compare, if current time is larger then end time, thus current time has passed end time like below.
if(currentTime>endTime){
//Do stuff
}
Enjoy..

Related

Calculate the time difference between two days of current week on Android

I would like to calculate the time difference between two days (e.g. Friday and Saturday) of the same week. This sort of calculation is required for validating a time restriction of my project. To understand more about the restriction see the below examples,
Example 1
{
"id": "3",
"from_day": "Fri",
"from_time": "16:00:00",
"to_day": "Sat",
"to_time": "06:00:00"
}
Example 2
{
"id": "4",
"from_day": "Mon",
"from_time": "04:00:00",
"to_day": "Mon",
"to_time": "09:00:00"
}
From the above example I've to verify if the running application passes between the exact date and time of the same week.
What I've done so far?
I've created this simple function which takes the "day of week" e.g Mon, "from time" e.g 04:00:00 and "to time" e.g 09:00:00 as parameter and returns if it's within the range.
public boolean getValidity(String day, String dateStart, String dateStop) {
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
String current_day = new SimpleDateFormat("EE", Locale.ENGLISH)
.format(date.getTime());
if (current_day.matches(day)) {
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("GMT+8"));
Date today = Calendar.getInstance().getTime();
String datePresent = format.format(today);
Date d1 = null;
Date d2 = null;
Date d3 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
d3 = format.parse(datePresent);
} catch (Exception e) {
e.printStackTrace();
}
long current_time = d3.getTime();
long start_time = d1.getTime();
long stop_time = d2.getTime();
if (current_time >= start_time && current_time <= stop_time) {
return true;
} else {
return false;
}
}
return false;
}
// this function is used for converting the time into GMT +8 before passing as a parameter in the getValidity() function
public String toGMT(String time){
//first convert the received string to date
Date date = null;
//creating DateFormat for converting time from local timezone to GMT
DateFormat format = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
try {
date = format.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
//getting GMT timezone, you can get any timezone e.g. UTC
format.setTimeZone(TimeZone.getTimeZone("GMT+8"));
return format.format(date).toString();
}
But the above code doesn't works for the first example where the dates are different. It would be extremely helpful if anyone can give some idea of solving the issue.
You can turn a date object into a long (milliseconds since Jan 1, 1970), and then use TimeUnit to get the number of seconds:
long diffInMs = endDate.getTime() - startDate.getTime();
long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMs);
end date and start date as date object for your days which you can do self.

determine if current time in java is past a predetermined time by 15mins

I would like to determine when the current time equals a defined time + 15mins.
The defined time here is in the format:
private Date fajr_begins;
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
fajr_begins = new Time(formatter.parse(prayerTimes.get(0)).getTime());
The code I have come up so far, which is not working is (the code below is crappy I know
DateTime today = new DateTime();
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
now1 = new Time(formatter.parse(today));
Duration duration = new Duration(sunrise, now1);
System.out.println(" time to duha " + duration);
The context of the question is a little light. Do you want to use a thread, do you want to be alerted...?
However, as a basic example you could do something like...
// The time we want the alert...
String time = "16:00";
// The date String of now...
String date = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
try {
// The date + time to give us context
Date timeAt = sdf.parse(date + " " + time);
boolean rollOver = false;
// Determine if the time has already passed, if it has
// we need to roll the date to the next day...
if (timeAt.before(new Date())) {
rollOver = true;
}
// A Calendar with which we can manipulate the date/time
Calendar cal = Calendar.getInstance();
cal.setTime(timeAt);
// Skip 15 minutes in advance
cal.add(Calendar.MINUTE, 15);
// Do we need to roll over the time...
if (rollOver) {
cal.add(Calendar.DATE, 1);
}
// The date the alert should be raised
Date alertTime = cal.getTime();
System.out.println("Raise alert at " + alertTime);
// The timer with which we will wait for the alert...
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
System.out.println("duha");
}
}, alertTime);
} catch (ParseException ex) {
}
Now, before you complain about the Date, everything is relative. Without the Date part of the time, it's difficult to know when we should raise our alert. The Date just helps us pinpoint the when the alert should be raised...
Additional
Context is everything, for example...if we use the following...
String time = "16:00";
try {
Date timeAt = new SimpleDateFormat("HH:mm").parse(time);
System.out.println(timeAt);
} catch (ParseException ex) {
ex.printStackTrace();
}
The timeAt value be Thu Jan 01 16:00:00 EST 1970, which is really useless, the time will always be before now...
If, instead, we use something like...
String time = "16:00";
String date = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
try {
Date timeAt = new SimpleDateFormat("dd/MM/yyyy HH:mm").parse(date + " " + time);
System.out.println(timeAt);
} catch (ParseException ex) {
ex.printStackTrace();
}
The timeAt will now be Thu Sep 05 16:00:00 EST 2013 which gives us some context to now
Now if we use Calendar to advance the time by 15 minutes...
Calendar cal = Calendar.getInstance();
cal.setTime(timeAt);
cal.add(Calendar.MINUTE, 15);
Date checkTime = cal.getTime();
System.out.println(checkTime);
The checkTime becomes Thu Sep 05 16:15:00 EST 2013. I use Calendar because it will automatically roll the hour and date for me should it need to be...
This now allows us to start using the default available API functionality. Because it's highly unlikely that the milliseconds will ever match, I would be temtered to do something like...
Calendar watchFor = Calendar.getInstance();
watchFor.setTime(timeAt);
watchFor.set(Calendar.MILLISECOND, 0);
watchFor.set(Calendar.SECOND, 0);
Calendar now = Calendar.getInstance();
now.setTime(new Date());
now.set(Calendar.MILLISECOND, 0);
now.set(Calendar.SECOND, 0);
if (watchFor.equals(now)) {
System.out.println("Go for it...");
}
Zeroing out the milliseconds and seconds, so I can compare the Date and time (HH:mm) alone.
You could of course compare the milliseconds directly as well...
Is this you want to do? Following sentence I got in that way.
I would like to determine when the current time equals a defined time + 15mins.
you can simply do as follows
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
Date preDefineTime=formatter.parse("10:00");
long additionMin=15*60*1000;
System.out.println(formatter.format(preDefineTime.getTime()+additionMin));

Time convert to timestamp

I have a log in timeformat
31/Mar/2013:17:03:30 -0700
I want to convert it into a timestamp here -70 in timezone. How can I do that?
try {
String time = myMap.get("timestamp");
String splitTime[] = time.split("-");//input Timestamp 31/Mar/2013:17:03:30 -0700
Date date = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss").parse(splitTime[0]);
myMap.put("timestamp", String.valueOf(new Long(date.getTime() / 1000)));
} catch (ParseException e) {
e.printStackTrace();
}
How do I use this timezone?
try this
Date date = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z").parse(s);
note that it will only parse /Mar/ if your default language is English, otherwise use
Date date = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z", Locale.US).parse(s);
Well you can use that time zone information to subtract/add that much time to your date:
String time = myMap.get("timestamp");
String splitTime[] = time.split("-");//input Timestamp 31/Mar/2013:17:03:30 -0700
Date date = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss").parse(splitTime[0]);
long timestamp = date.getTime() / 1000; ///datetime in seconds
long timezonehour = Long.parseLong(splitTime[1].substring(0,1)); // 07
long timezoneminutes = Long.parseLong(splitTime[1].substring(2,3)); // 00
timezonehour += timezoneminutes/60;
long timezone_seconds = (timezonehour/60)/60; // in seconds
timestamp += timezone_seconds // final computed value
I know this looks ugly but can't help further.

How to find the difference between two times in Android / Java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calculating the Difference Between Two Java Date Instances
i have two date values in two textboxes in string datatypes in HH:MM:SS format.HOw can i find difference between them and get result in HH:MM:SS?please help me...as fast as possible....!
Try this:
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date date1 = (Date) format.parse("4:15:20");
Date date2 = (Date) format.parse("2:30:30");
//time difference in milliseconds
long timeDiff = date1.getTime() - date2.getTime();
//new date object with time difference
Date diffDate = new Date(timeDiff);
//formatted date string
String timeDiffString = format.format(diffDate);
System.out.println("Time Diff = "+ timeDiffString );
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Above code has certain limitations. Other proper way could be to convert the long value of time difference manually in the string as below:
long timeDiffSecs = timeDiff/1000;
String timeDiffString = timeDiffSecs/3600+":"+
(timeDiffSecs%3600)/60+":"+
(timeDiffSecs%3600)%60;
System.out.println("Time Diff = "+ timeDiffString);
The code you have will give you the number of milliseconds difference between the listed dates. It could be that the answer could be simply divide by 1000 to get the number of seconds.
First Convert String date into simple Date formate
public String getconvertdate1(String date)
{
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
inputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
DateFormat outputFormat = new SimpleDateFormat("dd MMM yyyy");
Date parsed = new Date();
try
{
parsed = inputFormat.parse(date);
}
catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
String outputText = outputFormat.format(parsed);
return outputText;
}
//now can do anything with date.
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
long days = diff / (24 * 60 * 60 * 1000);// you get day difference between
AND use simpledateFormate to configure HH:MM:SS

Cannot add Timestamps

Why is getTime() having an error? I have tried everything, but cannot figure out what the problem is. As far as I know, I have converted the String arrayOpportunity[2] into a date. (It was originally a String.) Thanks!
SimpleDateFormat df = new SimpleDateFormat();
df.applyPattern("yyyy-MM-dd HH:mm:ss");
// Calendar timestamp = Calendar.getInstance();
// timestamp.setTime(df.parse(arrayOpportunity2)[0]);
arraySuspects.add(arrayGPS[0]);
// }
// long timediff = coord2.getTimestamp().getTimeInMillis() -
// coord1.getTimestamp().getTimeInMilis();
Date convertedDate = df.parse(arrayOpportunity[2]);
Date duration = df.parse("0000-00-00 00:14:59");
Date lastTime = df.parse(arrayOpportunity[2]);
// SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/mm/dd");
System.out.println(arrayOpportunity[2]);
// arrayOpportunity[2].setTime(arrayOpportunity[2].getTime() + duration);
// lastTime += duration;
arrayOpportunity[2].setTime(arrayOpportunity[2].getTime() + (((14 * 60) + 59)* 1000));
Calling df.parse(arrayOpportunity[2]); does not convert arrayOpportunity[2] to a Date, it assigns that value to lastTime. In your code call lastTime.getTime() instead of arrayOpportunity[2].getTime() as arrayOpportunity[2] is still a String
// Create your date parser
SimpleDateFormat df = new SimpleDateFormat();
// Set the date pattern
df.applyPattern("yyyy-MM-dd HH:mm:ss");
// Create a Date object by parsing the value of arrayOpportunity[2]
Date lastTime = df.parse(arrayOpportunity[2]);
// Set a new value to the Date object by performing a calculation on the result of getTime()
lastTime.setTime(lastTime.getTime() + (((14 * 60) + 59)* 1000));

Categories

Resources