I don't understand getNextIncludedTime() in Quartz - java

I'm probably just being an idiot - it's been a long day! I've misunderstood something in my first foray into Quartz...
Given this code:
DateTime dt = new DateTime();
dt = dt.withDayOfMonth(20);
Calendar cal = new CronCalendar("0 0/10 * * * ?" );
long start = dt.getMillis();
System.out.println("Starting at " + start);
long end = start + 10;
long current = start;
int i = 0;
while (current < end) {
if (i > 0) {
System.out.println(i + ":" + current);
}
long next = cal.getNextIncludedTime(current);
current = next;
i++;
}
I expect that there will be at most one included time in the output, as the time window is 10ms and the times included in the Calendar are 10 minutes apart.
But when I run it:
Starting at 1250796103004
1:1250796103005
2:1250796103006
3:1250796103007
4:1250796103008
5:1250796103009
6:1250796103010
7:1250796103011
8:1250796103012
9:1250796103013
Please help!

Yep, just me being a dumbass.
Calendars specify EXCLUDED times.
I should have been using a CronTrigger to specify the times I wanted to include. The code should look more like this...
CronTrigger cal = new CronTrigger("Test", "Test", "0 0/10 * * * ?" );
...
end = start + 1000000;
...
while (current < end) {
if (i > 0) {
System.out.println(i + ":" + current);
}
Date next = cal.getFireTimeAfter(new Date(current));
current = next.getTime();
i++;
}
Which gives the output I was expecting.
Starting at 1250798091337
1:1250798400000
2:1250799000000

Related

Android Java handler.postDelayed() remainingTime returns wrong value

I want to be able to calculate remaining time of myHandler2.postDelayed(). I was using this answer but it returns wrong value. Here is my code where the startTime variable is:
public void attackOnChibi(ChibiCharacter cc, boolean able) {
runnable = () -> {
Log.i("a", "a");
};
if (able) {
startTime = System.nanoTime();
myHandler2.postDelayed(runnable, count += 2000);
}
if (!able) {
myHandler2.removeCallbacksAndMessages(null);
count = 0;
}
}
And the code when I calculates and displays this remaining time:
elapsedTime = System.nanoTime() - gs.enemies.get(gs.enemyId - 1).startTime;
remainingTime = gs.enemies.get(gs.enemyId - 1).count + 2000 - TimeUnit.MILLISECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS);
Log.i("elapsed/remaining", elapsedTime + " " + remainingTime);
Why it does not work? Help me please...

How to sum total number of hours ,minutes,seconds in java?

Am having a doubt on how to sum total number of hours minutes seconds in java for example i have 160:00:00 and 24:00:00 and 13:50:00 and 00:10:00 i need to get grand sum like 198:00:00 how can i calculate this so far what i have tried is
for(int i=0;i<addnoteobj.size();i++){
String s = addnoteobj.get(i).getDuration();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String[] tokens = s.split(":");
int hours = Integer.parseInt(tokens[0]);
int minutes = Integer.parseInt(tokens[1]);
int seconds = Integer.parseInt(tokens[2]);
duration = 3600 * hours + 60 * minutes + seconds;
int j = duration/3600;
int h= (duration%3600) / 60;
int m = (duration % 60);
hourss=hourss+j;
mm=mm+h;
sss=sss+m;
date3 = hourss + ":" + mm + ":" + ss;
String time = simpleDateFormat.format(new Date(duration*1000L));
Log.d("dat",time);
try {
date=simpleDateFormat.parse(s);
ss=ss+date.getTime();
date3 = simpleDateFormat.format(new Date(ss));
// total=dates.getTime();
Log.d("time",date3);
} catch (ParseException e) {
e.printStackTrace();
}
}
But i cannot achieve this how to do this am having total hours in list how to get total hours thanks in advance
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time, the modern Date-Time API:
You can use java.time.Duration which is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation. With Java-9 some more convenient methods were introduced.
Assuming all the string are in the form of HH:mm:ss format, you can split them on : and then combine the parts to form a string in the ISO 8601 pattern for a duration which can be parsed using Duration#parse.
Demo:
import java.time.Duration;
public class Main {
public static void main(String[] args) {
String[] strDurationArr = {
"160:00:00",
"24:00:00",
"13:50:00",
"00:10:00"
};
Duration sum = Duration.ZERO;
for (String strDuration : strDurationArr) {
sum = sum.plus(parseStrDuration(strDuration));
}
System.out.println(formatDurationJava8Plus(sum));
System.out.println(formatDurationJava9Plus(sum));
}
static Duration parseStrDuration(String strDuration) {
String[] arr = strDuration.split(":");
String strIsoDuration = "PT" + arr[0] + "H" + arr[1] + "M" + arr[2] + "S";
return Duration.parse(strIsoDuration);
}
static String formatDurationJava8Plus(Duration duration) {
return String.format("%d:%02d:%02d", duration.toHours(), duration.toMinutes() % 60, duration.toSeconds() % 60);
}
static String formatDurationJava9Plus(Duration duration) {
return String.format("%d:%02d:%02d", duration.toHours(), duration.toMinutesPart(), duration.toSecondsPart());
}
}
Output:
198:00:00
198:00:00
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
I have intentionally left the println so that you can see the code flow. hope this helps you...
public static void main(String[] args) {
String time[] = { "160:00:00", "24:00:00", "13:50:00", "00:10:00" };
int hours = 0, minutes = 0, seconds = 0;
for (String string : time) {
String temp[] = string.split(":");
hours = hours + Integer.valueOf(temp[0]);
minutes = minutes + Integer.valueOf(temp[1]);
seconds = seconds + Integer.valueOf(temp[2]);
}
System.out.println(hours + ":" + minutes + ":" + seconds);
if (seconds == 60) {
minutes = minutes + 1;
seconds = 0;
} else if (seconds > 59) {
minutes = minutes + (seconds / 60);
seconds = seconds % 60;
}
System.out.println(hours + ":" + minutes + ":" + seconds);
if (minutes == 60) {
hours = hours + 1;
minutes = 0;
} else if (minutes > 59) {
hours = hours + (minutes / 60);
minutes = minutes % 60;
}
System.out.println(hours + ":" + minutes + ":" + seconds);
String output = "";
output = String.valueOf(hours);
output = output.concat(":" + (String.valueOf(minutes).length() == 1 ? "0" + String.valueOf(minutes) : String.valueOf(minutes)));
output = output.concat(":" + (String.valueOf(seconds).length() == 1 ? "0" + String.valueOf(seconds) : String.valueOf(seconds)));
System.out.println(output);
}
I didn't test it but I'm pretty sure it's something like this:
private static String sumTime(String t1, String t2){
byte extraMinutes=0;
byte extraHours=0;
String arrt1[] = t1.split(":");
String arrt2[] = t2.split(":");
int seconds = Integer.valueOf(arrt1[2]) + Integer.valueOf(arrt2[2]);
if(seconds>=60) {
extraMinutes = 1;
seconds = seconds % 60;
}
int minutes = Integer.valueOf(arrt1[1]) + Integer.valueOf(arrt2[1]) + extraMinutes;
if(minutes>=60){
extraHours = 1;
minutes = minutes % 60;
}
int hours = Integer.valueOf(arrt1[0]) + Integer.valueOf(arrt2[0]) + extraHours;
if(hours>=24) hours = hours%24;
return hours+":"+minutes+":"+seconds;
}

add string time with overflow hour in java

I want to add string time with format HH:mm:ss and special hour field. Example :
"20:15:30" (string) add "13:50:35" (string) -> result i want : "34:06:05" (string).
I have search similar code :
String time1="20:15:30";
String time2="13:50:35";
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date1 = timeFormat.parse(time1);
Date date2 = timeFormat.parse(time2);
long sum = date1.getTime() + date2.getTime();
String date3 = timeFormat.format(new Date(sum));
System.out.println("The sum is "+ date3);
And result of above code : The sum is 10:06:05 not i want. How is easy way to do this ?
You could simply take advantage of either Java 8's or Joda Time's duration capabilities.
For example, this simply creates a duration which is the sum of the number of seconds of the two times
LocalTime lt1 = LocalTime.parse("20:15:30", DateTimeFormatter.ofPattern("HH:mm:ss"));
LocalTime lt2 = LocalTime.parse("13:50:35", DateTimeFormatter.ofPattern("HH:mm:ss"));
//long t = lt1.toSecondOfDay() + lt2.toSecondOfDay();
//Duration duration = Duration.ofSeconds(t);
Duration duration = Duration.between(lt2, lt1);
System.out.println(formatDuration(duration));
Which prints out 34:06:05
formatDuration method
public static String formatDuration(Duration duration) {
long hours = duration.toHours();
duration = duration.minusHours(hours);
long minutes = duration.toMinutes();
duration = duration.minusMinutes(minutes);
long seconds = duration.getSeconds();
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
SimpleDateFormat can't do that, but you can do it yourself, by parsing the input with a regular expression, and formatting the output with the format method.
private static String addTime(String ... times) {
if (times.length < 2)
throw new IllegalArgumentException("At least 2 times are required");
Pattern timePattern = Pattern.compile("([0-9]+):([0-5][0-9]):([0-5][0-9])");
// Parse times and sum hours, minutes, and seconds
int hour = 0, minute = 0, second = 0;
for (String time : times) {
Matcher m = timePattern.matcher(time);
if (! m.matches())
throw new IllegalArgumentException("Invalid time: " + time);
hour += Integer.parseInt(m.group(1));
minute += Integer.parseInt(m.group(2));
second += Integer.parseInt(m.group(3));
}
// Handle overflow
minute += second / 60; second %= 60;
hour += minute / 60; minute %= 60;
// Format and return result
return String.format("%02d:%02d:%02d", hour, minute, second);
}
Test
System.out.println(addTime("20:15:30", "13:50:35"));
System.out.println(addTime("20:15:30", "13:50:35", "20:15:30", "13:50:35"));
System.out.println(addTime("98765:43:21", "12:34:56"));
Output
34:06:05
68:12:10
98778:18:17

Java time difference

Getting the timestamp from mysql it returns something like this "2014-03-19 12:00:43" and in java I'm wanting to get the difference from the timestamp and the current time.
New to java and very unfamiliar, here is what I had in php though.... anything similar that would achieve the same thing
date_def
New to java and very unfamiliar, here is what I had in php though.... anything similar that would achieve the same thing
date_default_timezone_set('America/New_York');
$server = timesince($row['timestamp']);
function timesince($time){
$seconds = strtotime($time) - time();
$days = floor($seconds/ -86400);
$seconds %= 86400;
New to java and very unfamiliar, here is what I had in php though.... anything similar that would achieve the
New to java and very unfamiliar, here is what I had in php though.... anything similar that would achieve the same thing
date_default_timezone_set('America/New_York');
$server = timesince($row['timestamp']);
New to java and very unfamiliar, here is what I had in php though.... anything similar that would achieve the same thing
New to java and very unfamiliar, here is what I had in php though.... anything similar that would achieve the same thing
date_default_timezone_set('America/New_York');
$server = timesince($row['timestamp']);
function timesince($time){
$seconds = strtotime($time) - time();
$days = floor($seconds/ -86400);
$seconds %= 86400;time();
$days = floor($seconds/ -86400);
$seconds %= 86400;
function timesince($time){
$seconds = strtotime($time) - time();
$days = floor($seconds/ -86400);
$seconds %= 86400;
$seconds = strtotime($time) - time();
$days = floor($seconds/ -86400);
$seconds %= 86400;ault_timezone_set('America/New_York');
New to java and very unfamiliar, here is what I had in php though.... anything similar that would achieve the same thing
date_default_timezone_set('America/New_York');
$server = timesince($row['timestamp']);
function timesince($time){
$seconds = strtotime($time) - time();
$days = floor($seconds/ -86400);
$seconds %= 86400;
$minutes = floor($seconds / -60);
$seconds %= 60;
$seconds *= -1;
if ($days > 360){
return "Not voted here yet.";
}
if($days > 1){
$days = $days." days, ";
} elseif ($days == 1){
$days = $days." day, ";
} else {
$days = "";
}
if($hours > 1){
$hours = $hours." hours, ";
}elseif ($hours == 1){
$hours = $hours." hour, ";
} else {
$hours = "";
}
if($minutes > 1){
$minutes = $minutes." minutes and ";
}elseif ($minutes == 1){
$minutes = $minutes." minute and ";
}else {
$minutes = "";
}
if($seconds > 1){
$seconds = $seconds." seconds";
}elseif ($seconds == 1){
$seconds = $seconds." second";
}
return $days.$hours.$minutes.$seconds." ago";
}
I don't see anything similar to strtotime in java, and don't want to use any additional libraries.
Also in the php script I have at the top
date_default_timezone_set('America/New_York');
so it gets the right time difference with timezone accounted for.
Where to start with doing something similar in java though?
Javascript's native Date object is able to replicate php's strtodate function very easily.
To call it, you would simply use:
var d = new Date(dateString);
(See http://www.w3schools.com/jsref/jsref_obj_date.asp for more information)
So you could use a function such as:
function timesince( dateString ) {
var originalTime = new Date(); // The time you provided in milliseconds converted to javascript object
var currentTime = new Date(); // The current time as a javascript object
return millisecondDifference = parseFloat(currentTime.getTime()) - parseFloat(originalTime.getTime());
// returns the difference in milliseconds between the current time and the original time
// parseFloat is used to ensure that the values returned are read by javascript as floats (numbers) and thus can have math operations performed on them
}
to return the difference in milliseconds. Then if you'd like to convert that to "Human Readable" format, you could use a new Date object as follows:
var diffRaw = timesince( '2014-03-19 12:00:43' );
var diff = new Date(diffRaw);
var seconds = diff.getSeconds() // Seconds from 0 - 59
var minutes = diff.getMinutes() // Minutes from 0 - 59
var hours = diff.getHours() // Hours from 0 - 23
var day = diff.getDay() // Days from 0 - 6
var date = diff.getDate() // Date from 1 - 31
var month = diff.getMonth() // Months from 0 - 11
var year = diff.getFullYear() // XXXX year starting from 1970
To replicate the function you have written exactly, you could use the following function:
function timesince( dateString ) {
var originalTime = new Date(dateString);
var currentTime = new Date();
var diffRaw = millisecondDifference = parseFloat(currentTime.getTime()) - parseFloat(originalTime.getTime());
var diff = new Date(diffRaw);
var seconds = diff.getSeconds();
var minutes = diff.getMinutes();
var hours = diff.getHours();
var day = diff.getDay();
var date = diff.getDate() - 1;
var month = diff.getMonth();
var year = diff.getFullYear();
if( year !== 1970 ) {
return "Not voted here yet.";
}
var returnString = "";
if(month > 1 || month == 0) {
returnString += month + " months, ";
} else {
returnString += month + " month, ";
}
if(date > 1 || date == 0) {
returnString += date + " days, ";
} else {
returnString += date + " day, ";
}
if(hours > 1 || hours == 0) {
returnString += hours + " hours, ";
} else {
returnString += hours + " hour, ";
}
if(minutes > 1 || minutes == 0) {
returnString += minutes + " minutes, ";
} else {
returnString += minutes + " minute, ";
}
if(seconds > 1 || seconds == 0) {
returnString += seconds + " seconds, ";
} else {
returnString += seconds + " second, ";
}
return returnString;
}
You can find a working example here:
http://jsfiddle.net/MQPPw/
Don't do this in Java (or PHP, for that matter). This is something to be done in MySQL, using its date/time functions.
SELECT UNIX_TIMESTAMP() - UNIX_TIMESTAMP(my_timestamp_col) AS seconds_ago ...
The first method returns the current time as a unix timestamp (ie, seconds since epoch). The second method returns the my_timestamp_col time as a unix timestamp. Subtract the two, and you have how many seconds ago my_timestamp_col was.
EDIT: This gets more complicated when you factor in timezones, as Alexander points out. One option is to use the CONVERT_TZ function to get your my_timestamp_col to UTC, and then call UNIX_TIMESTAMP on that:
UNIX_TIMESTAMP(CONVERT_TZ(timestamp, '-5:00', '+0:00'))
Another option would be to do this on the Java side, after all: get the field as a Date, which should do the timezone conversion for you; then call its getTime() method to get milliseconds since epoch, and subtract that from System.currentTimeMillis(). That gives you how many milliseconds ago the event happened.

Converting date into text format

How do I convert date into its text format..for ex:if updated today..then instead of date it must show "Today",one day after it must show "Yesterday",and then after two days..it must display the date in general form(//_) on which it was updated..i tried using SimpleDateFormat..but not working..
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date d= new Date();
//Convert Date object to string
String strDate = sdf.format(d);
System.out.println("Formated String is " + strDate);
d = sdf.parse("31-12-2009");
Plz help..
Thanks in advance..
Try this:
public class TimeUtils {
public final static long ONE_SECOND = 1000;
public final static long SECONDS = 60;
public final static long ONE_MINUTE = ONE_SECOND * 60;
public final static long MINUTES = 60;
public final static long ONE_HOUR = ONE_MINUTE * 60;
public final static long HOURS = 24;
public final static long ONE_DAY = ONE_HOUR * 24;
private TimeUtils() {
}
/**
* converts time (in milliseconds) to human-readable format
* "<w> days, <x> hours, <y> minutes and (z) seconds"
*/
public static String millisToLongDHMS(long duration) {
StringBuffer res = new StringBuffer();
long temp = 0;
if (duration >= ONE_SECOND) {
temp = duration / ONE_DAY;
if (temp > 0) {
duration -= temp * ONE_DAY;
res.append(temp).append(" day").append(temp > 1 ? "s" : "")
.append(duration >= ONE_MINUTE ? ", " : "");
}
temp = duration / ONE_HOUR;
if (temp > 0) {
duration -= temp * ONE_HOUR;
res.append(temp).append(" hour").append(temp > 1 ? "s" : "")
.append(duration >= ONE_MINUTE ? ", " : "");
}
temp = duration / ONE_MINUTE;
if (temp > 0) {
duration -= temp * ONE_MINUTE;
res.append(temp).append(" minute").append(temp > 1 ? "s" : "");
}
if (!res.toString().equals("") && duration >= ONE_SECOND) {
res.append(" and ");
}
temp = duration / ONE_SECOND;
if (temp > 0) {
res.append(temp).append(" second").append(temp > 1 ? "s" : "");
}
return res.toString();
} else {
return "0 second";
}
}
public static void main(String args[]) {
System.out.println(millisToLongDHMS(123));
System.out.println(millisToLongDHMS((5 * ONE_SECOND) + 123));
System.out.println(millisToLongDHMS(ONE_DAY + ONE_HOUR));
System.out.println(millisToLongDHMS(ONE_DAY + 2 * ONE_SECOND));
System.out.println(millisToLongDHMS(ONE_DAY + ONE_HOUR + (2 * ONE_MINUTE)));
System.out.println(millisToLongDHMS((4 * ONE_DAY) + (3 * ONE_HOUR)
+ (2 * ONE_MINUTE) + ONE_SECOND));
System.out.println(millisToLongDHMS((5 * ONE_DAY) + (4 * ONE_HOUR)
+ ONE_MINUTE + (23 * ONE_SECOND) + 123));
System.out.println(millisToLongDHMS(42 * ONE_DAY));
/*
output :
0 second
5 seconds
1 day, 1 hour
1 day and 2 seconds
1 day, 1 hour, 2 minutes
4 days, 3 hours, 2 minutes and 1 second
5 days, 4 hours, 1 minute and 23 seconds
42 days
*/
}
}
Take a look at the PrettyTime library.
You can check this Comparision of dates
import java.text.SimpleDateFormat;
import java.util.Date;
public class App {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
public static long ms, s, m, h, d, w;
static {
ms = 1;
s = ms * 1000;
m = s * 60;
h = m * 60;
d = h * 24;
w = d * 7;
}
public App() {
Date now = new Date();
Date old = new Date();
try {
old = sdf.parse("12-11-2013");
} catch (Exception e) {
e.printStackTrace();
}
long diff = now.getTime() - old.getTime();
if (diff < this.d) {
System.out.println("Today");
}
else if (diff > this.d && diff < this.d*2) {
System.out.println("Yesterday");
}
System.out.println("Difference: " + msToHms(diff));
}
public String msToHms(long ms) {
int seconds = (int) (ms / this.s) % 60 ;
int minutes = (int) ((ms / this.m) % 60);
int hours = (int) ((ms / this.h) % 24);
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
public static void main(String[] args) {
new App();
}
}
Output
Yesterday
Difference: 07:11:22
You have to implement your own logic based on the time difference and use the corresponding date format.
Lets assume you are getting a date from a server.
Get the device's time and compare to your date.
For your requirements there will be two cases.
The difference between the two date is less then a day, then return "Today" string.
The difference between the two date is grater then a day then use the Simple Date format to format your date as you want.
For comparing dates please see this entry: datecompare

Categories