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

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.

Related

Check between two datetime if passed in Java/Android

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..

Calculate no of days between two dates in java [duplicate]

This question already has answers here:
Android/Java - Date Difference in days
(18 answers)
Closed 6 years ago.
I need to calculate number of days between two dates and I am using below code. problem is it is returning me 2 but actually it should return 3 because difference between 30 june 2016 to 27 june is 3. can you please help where it should include current date as well in difference?
public static long getNoOfDaysBtwnDates(String expiryDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
long diff = 0;
long noOfDays = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Date createdDate = new Date();
diff = expDate.getTime() - createdDate.getTime();
noOfDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
long a = TimeUnit.DAYS.toDays(noOfDays);
// logger.info("No of Day after difference are - " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
System.out.println(a);
System.out.println(noOfDays);
} catch (ParseException e) {
e.printStackTrace();
}
return noOfDays;
}
expiry date is 2016-06-30 and current date is 2016-06-27
Reason is, you are not subtracting two dates with same time format.
Use Calendar class to change the time as 00:00:00 for both date and you will get exact difference in days.
Date createdDate = new Date();
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 0);
time.set(Calendar.MINUTE, 0);
time.set(Calendar.SECOND, 0);
time.set(Calendar.MILLISECOND, 0);
createdDate = time.getTime();
More explaination in Jim Garrison' answer
Why not use LocalDate?
import java.time.LocalDate;
import static java.time.temporal.ChronoUnit.DAYS;
long diffInDays(LocalDate a, LocalDate b) {
return DAYS.between(a, b);
}
The problem is that
Date createdDate = new Date();
sets createdDate to the current instant, that is, it includes the current time as well as the date. When you parse a string using the given format, the time is initialized to 00:00:00.
Let's say you ran this at exactly 18:00 local time, you end up with
createdDate = 2016-06-27 18:00:00.000
expDate = 2016-06-30 00:00:00.000
The difference is 2 days 6 hours, not 3 days.
You should be using the newer java.time.* classes from Java 8. There is a class LocalDate that represents dates without time-of-day. It includes methods for parsing using a format, and LocalDate.now() to get the current date, as well as methods for calculating intervals between LocalDate instances.
Using the Calendar.get(Calendar.DAY_OF_MONTH) as pointed out by python:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
String expiryDate ="2016-06-30";
int diff = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Calendar cal = Calendar.getInstance();
int today = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(expDate);
diff = cal.get(Calendar.DAY_OF_MONTH)- today;
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(diff);

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.

converting a date string into milliseconds in java [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Calculate date/time difference in java
how would a future date such as Sat Feb 17 2012 be converted into milliseconds in java that can then be subtracted from the current time in milliseconds to yield time remaining until that future date.
The simplest technique would be to use DateFormat:
String input = "Sat Feb 17 2012";
Date date = new SimpleDateFormat("EEE MMM dd yyyy", Locale.ENGLISH).parse(input);
long milliseconds = date.getTime();
long millisecondsFromNow = milliseconds - (new Date()).getTime();
Toast.makeText(this, "Milliseconds to future date="+millisecondsFromNow, Toast.LENGTH_SHORT).show();
A more difficult technique (that basically does what DateFormat does for you) involves parsing it yourself (this would not be considered best practice):
String input = "Sat Feb 17 2012";
String[] myDate = input.split("\\s+");
int year = Integer.parseInt(myDate[3]);
String monthString = myDate[1];
int mo = monthString.equals("Jan")? Calendar.JANUARY :
monthString.equals("Feb")? Calendar.FEBRUARY :
monthString.equals("Mar")? Calendar.MARCH :
monthString.equals("Apr")? Calendar.APRIL :
monthString.equals("May")? Calendar.MAY :
monthString.equals("Jun")? Calendar.JUNE :
monthString.equals("Jul")? Calendar.JULY :
monthString.equals("Aug")? Calendar.AUGUST :
monthString.equals("Sep")? Calendar.SEPTEMBER :
monthString.equals("Oct")? Calendar.OCTOBER :
monthString.equals("Nov")? Calendar.NOVEMBER :
monthString.equals("Dec")? Calendar.DECEMBER : 0;
int day = Integer.parseInt(myDate[2]);
Calendar c = Calendar.getInstance();
c.set(year, mo, day);
long then = c.getTimeInMillis();
Time current_time = new Time();
current_time.setToNow();
long now = current_time.toMillis(false);
long future = then - now;
Date d = new Date(future);
//TODO use d as you need.
Toast.makeText(this, "Milliseconds to future date="+future, Toast.LENGTH_SHORT).show();
Firts, you must parse you String to get its Date representation. Here are examples and some docs.
Then you shoud call getTime() method of your Date.
DateFormat format = new SimpleDateFormat("EEE MMM dd yyyy", Locale.US);
long futureTime = 0;
try {
Date date = format.parse("Sat Feb 17 2012");
futureTime = date.getTime();
} catch (ParseException e) {
Log.e("log", e.getMessage(), e);
}
long curTime = System.currentTimeMillis();
long diff = futureTime - curTime;
Pass year, month and day of the future date in the date of this code and variable diff will give the millisecond time till that date,
Date date = new GregorianCalendar(year, month, day).getTime();
Date today = new Date();
long diff = date.getTime() - today.getTime();
You can simply call the getTime() method of date object. please follow through the sample below
import java.util.Date;
public class Test {
#SuppressWarnings("deprecation")
public static void main(String[] args) {
System.out.println(new Date("Sat Feb 17 2012").getTime());
}
}
try { String str_date="11-June-07";
SimpleDateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MMM-yy");
date = (Date) formatter.parse(str_date);
Log.i("test",""+date);
} catch (Exception e)
{System.out.println("Exception :"+e); }
Date d = new Date();
long time = d.getTime();
long timeDiff = time - lastTime;
//timeDiff will contain your value.
//import these two,
//import java.text.SimpleDateFormat;
//import java.util.Date;

Categories

Resources