Math with MySQL timestamps in groovy - math

I need to subtract one timestamp from another in groovy and get the number of hours that has passed. The timestamps are coming from MySQL. When I do simple math I get numbers of days rounded off to zero integers.
endDate - startDate
gives rounded integer
I want a result of 2.35 hours, etc.

You can use groovy.time.TimeCategory like so:
// create two timestamps
import java.sql.Timestamp
def dates = ['2012/08/03 09:00', '2012/08/03 10:30']
def (Timestamp a, Timestamp b) = dates.collect {
new Timestamp( Date.parse( 'yyyy/MM/dd hh:mm', it ).time )
}
// Then compare them with TimeCategory
use(groovy.time.TimeCategory) {
def duration = b - a
println "${duration.days}d ${duration.hours}h ${duration.minutes}m"
}
Which will print:
0d 1h 30m

Related

Opensearch painless calculate elpased time between two timestamp

I have start and end timestamp, and I want to calculate the elpased time between them.
I created a dinamic field elapsed-time:
def result = 0;
def endTimestamp = doc['endTimestamp'].value.millis;
def startTimestamp = doc['startTimestamp'].value.millis;
return (endTimestamp - startTimestamp );
When I discover data, the elapsed time has always bad hours, but minutes and seconds are right.
What I am doing wrong?

Subtract number of hours from current time in Java

I have a string that represents time duration of 54:34:41 i.e. 54 hours, 34 minutes, 41 seconds.
I would like to extract the 54 hours and subtract it from the current system time.
However when I run below I get java.time.format.DateTimeParseException: Text '54:34:41' could not be parsed: Invalid value for HourOfDay (valid values 0 - 23): 54
How can I extract 54 hours and subtract from current time?
private val formatterForTime: DateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss")
val timeDuration = formatterForTime.parse("54:34:41")
val currentTime = LocalDateTime.now()
val newTime = currentTime.minusHours(timeDuration.get(ChronoField.HOUR_OF_DAY).toLong())
tl;dr
ZonedDateTime
.now(
ZoneId.of( "Asia/Tokyo" )
)
.minusHours(
Integer.parseInt( "54:34:41".split( ":" )[0] )
)
Details
Parse hours
Get the number of hours.
int hours = Integer.parseInt( "54:34:41".split( ":" )[0] ) ;
ISO 8601
Your input text for a span-of-time does not comply with the ISO 8601 standard for date-time values. The java.time classes by default use the standard formats when parsing/generating text.
If instead of 54:34:41 you had PT54H34M41S, then we could use:
int hours = Duration.parse( "PT54H34M41S" ).toHours() ;
I recommend you stick with the standard format rather than the ambiguous clock-time format.
Capture current moment
Capture the current moment as seen in a particular time zone.
ZoneId z = ZoneId.of( "Africa/Casablanca" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Subtract hours
Subtract your hours.
ZonedDateTime earlier = zdt.minusHours( hours ) )

How to split two times using frequency in dart?

So, I need partition two times in dart(startTime and endTime) using an int value called frequency
Start time and End Time are DateTimes respectively. As for an example:
start time: 2021-07-20 10:00:00.000 // 10:00 AM
end time: 2021-07-20 16:00:00.000 // 04:00 PM
frequency: 30
so I need a list which will give my something like:
2021-07-20 10:30:00.000
2021-07-20 11:00:00.000
2021-07-20 11:30:00.000
2021-07-20 12:00:00.000
2021-07-20 12:30:00.000
.......
I have no idea what to do next. But I have created a method called returnTimeDifference which goes something like this:
Duration returnDuration (DateTime? startTime , DateTime? endTime) {
print(
"start time: $startTime \nend Time: $endTime",
);
Duration hourSpan;
workHourSpan = endTime!.difference(startTime !);
print(hourSpan);
return hourSpan;
}
For my above example the method will return 6:00:00.000000. I'm not sure if the value returned from the returnDuration can be used in any matter but I need help splitting the values of two date times into parts using the provided frequency.
N.B: Will it be easier to calculate the values if frequency was in actual Duration?
Repeatedly add your time interval to your start time in a loop until you reach the end time and collect the results. Using a Duration instead of an int for your time interval will be easier and will avoid ambiguity (in your example code, it's unclear if frequency represents a time in minutes, seconds, or if it's supposed to be the number if items you want in the resulting list).
Assuming that your start time and end time are meant to be exclusive endpoints, you could do:
/// Returns a list of [DateTime]s between (but not including) [start] and
/// [end], spaced by [period] intervals.
List<DateTime> getDateTimesBetween({
required DateTime start,
required DateTime end,
required Duration period,
}) {
var dateTimes = <DateTime>[];
var current = start.add(period);
while (current.isBefore(end)) {
dateTimes.add(current);
current = current.add(period);
}
return dateTimes;
}
void main() {
print(getDateTimesBetween(
start: DateTime(2021, 07, 20, 10),
end: DateTime(2021, 07, 20, 16),
period: Duration(minutes: 30),
));
}

comparison of two dates

how to compare values of 2 dates using actionscript
i executed this code in my program..
var time1:Date = new Date(Number(fromDate.substr(0,4)),Number(fromDate.substring(5,7))-1, Number(fromDate.substring(8,10)));
var time2:Date = new Date(Number(toDate.substr(0,4)),Number(toDate.substring(5,7))-1, Number(toDate.substring(8,10)));
if(time1.getTime() > time2.getTime())
{
Alert.show(time1 + ” is after ” + time2);
}
im getting error: Error: Unexpected end of token stream
AS3 doesn't support a time delta class like Python so this can actually be a little tricky. There are lots of things to be worried about when comparing dates:
daylight savings time (when the clocks change one hour in certain countries Spring and Fall)
time-zones
leap-years
The roughest way to do things is just to use the time property of a date object. This way you can get an accurate difference between two dates expressed in milliseconds:
var date1:Date = new Date(2001, 9, 12); // Oct. 12, 2001
var date2:Date = new Date(2010, 5, 22); // Jun. 22, 2010
var differenceInMilliseconds:Number = date2.time - date1.time;
Using this time property you can do things like check if one date is before or after another date. You can also do rough calculations on the distance between two dates by defining some constants:
const MILLISECOND_PER_SECOND:int = 1000;
const SECOND_PER_MINUTES:int = 60;
const MINUTES_PER_HOUR:int = 60;
const HOURS_PER_DAY:int = 24;
// ... etc ...
var differenceInSeconds:Number = differenceInMilliseconds / MILLISECOND_PER_SECOND;
var differenceInMinutes:Number = differenceInSeconds / SECOND_PER_MINUTES;
var differenceInHouse:Number = differenceInMinutes / MINUTES_PER_HOUR;
var differenceInDays:Number = differenceInHouse / HOURS_PER_DAY;
Once you get to the level of days you could get problems with daylight savings time since the change of 1 hour can make it seem like a full day has passed when it really hasn't. After days and into weeks or months you run into leap year problems.
Assuming your string processing code correctly gives you valid date objects, just use the ObjectUtil.dateCompare function to compare 2 dates:
http://livedocs.adobe.com/flex/3/langref/mx/utils/ObjectUtil.html#dateCompare%28%29
if( ObjectUtil.dateCompare(date1, date2) == 1 ){}
I'm pretty sure that the return types defined in the ASDocs are wrong.
It'll actually return -1 if a is null or before b; 1 if b is null or before.
If you have two dates as Date objects already, just compare them. e.g. a.getTime() > b.getTime().
If they are strings, see their format is acceptable by the default Date.parse() function. If not, you may have other work to do.
Let's see your values first, shall we?
private function differenceBetweenDates(date1:Date, date2:Date):Number{
var MS_PER_DAY:uint = 1000 * 60 * 60 * 24;
var tempDate:Date = new Date(date2.time - date1.time);
var difference:Number =
Math.abs(Math.round((tempDate.time / MS_PER_DAY)));
return difference;
}
I have achieved comparing dates succesfully using below code:
//here i have to compare two dates ,these are startdate and enddate.
// gets millisecs counts from 1970 midnight till sellected start date
var Starttimecounts : Number = popJobWin.DFStartDate.selectedDate.time;
// gets millisecs counts from 1970 midnight till sellected end date
var Endtimecounts : Number = popJobWin.DFEndDate.selectedDate.time ;
if (Starttimecounts > Endtimecounts)
{
Alert.show('end date should not lesser than start date..wrong!');
//replace your logic here
}
else
{
Alert.show('correct!');
//replace your logic here
}

retrievind date in asp.net

I need to retrieve the current date in asp.net and then compare that with the date given by the user in textbox1.text(mm/dd/yyyy format), if date date given is greater than current date then error else add 4months2days with that date and display it in textbox2.text.
help me please,
thanking you guys,
Indranil
DateTime dateToCompare;
if(DateTime.TryParse(textbox1.text, out dateToCompare))
{
DateTime current = DateTime.Now;
TimeSpan ts = current - dateToCompare;
if (ts.Ticks < 0)
{
//display error
}
else
textbox2.text = dateToCompare.AddMonths(4).AddDays(2).ToString("mm/dd/yyyy");
}
}
I'm not going to write your code, but in .NET you can use ToString to specify a date format, TryParse to get a date out of a string. And AddDays, AddMonths etc to manipulate a date.
In javascript, there's no simple way to format output, but you can use getMonth etc to prompt the individual values and concatenate a string from that. You can use a combination of getDate and setDate to manipulate dates. It automatically corrects for new months, i.e. if you run myDate.setDate( myDate.getDate() + 60 ) it'll actually increment by 60 days; you won't end up with a weird date like May 74th.
Keep in mind that months in javascript are zero-based, ie January is 0, February is 1, etc.
You can create a new date in javascript by new Date(yy, mm, dd) or new Date('yy/mm/dd'), so you could string-manipulate an input and create a date from that.
To compare two dates, you can subtract one from the other, and get the difference in milliseconds.
if ( dateA - dateB < 0 ) // dateB is greater than dateA (occurrs later)
and
var diff = Math.abs(dateA - dateB) // difference in ms, no matter which date is greater
DateTime date1 = new DateTime();
if(DateTime.TryParse(textbox1.text, out date1)){
if (date1.CompareTo(DateTime.Now) > 0)
{
//Error code here
}else
{
textbox2.text = date1.AddMonths(4).AddDays(2);
}
}

Resources