Variable cron in openHAB rule - openhab

In order to set an alarm from the GUI I would like to pass a variable as the argument to cron.
This works:
rule "Wake up"
when
Time cron "00 00 06 * * ?"
then
// ...
end
This does not work:
var morning = "00 00 06 * * ?"
rule "Wake up"
when
Time cron morning
then
// ...
end
Should this be possible to do?

The Cron string cannot be changed, but I use this code to get around it:
import org.joda.time.Duration
import org.quartz.CronExpression
var Timer wateringtimer = null
// Start watering at 03:00 AM, all days except Saturday (5)
val wateringCronString = "0 0 3 ? * 1,2,3,4,5,6"
...
rule "Set Cron"
...
var cronExpression = new CronExpression(wateringCronString)
var triggerTime = cronExpression.getNextValidTimeAfter(now.plusMinutes(1).toDate)
Seconds::secondsBetween(now,new DateTime(triggerTime)).getSeconds()
if (watertimer !== null)
watertimer.cancel()
wateringtimer = createTimer(now.plusSeconds(diff),
[
...Do something...
])

Related

Moment JS diff() returns 0 days between Oct 31 and 1 Nov

As is shown below moment.diff() incorrectly calculates 0 days between yesterday (31 October) and today (1 November). Is this a problem with momentJS or with NodeJS (v14.15.4)?
> a = moment(new Date('2021-10-31'))
Moment<2021-10-31T02:00:00+02:00>
> b = moment(new Date('2021-11-01'))
Moment<2021-11-01T01:00:00+01:00>
> a.diff(b, 'days')
0
> a.diff(b, 'hours')
-24
One possible cause could be the summer => winter change that officially happened from Sun 31 Oct to Mon 1 Nov*. This is evident from the parsing of '2021-10-31' to a summer time Moment<2021-10-31T02:00:00+02:00> (2h).
Nevertheless, I would argue 24 hours diff should not come out as 0 days and thus it's a bug in Moment.
* Though everyone actually sets their clocks back on Sunday 31 Oct... go figure.
I think it's because there was the change of hour and that in .diff() for get the hour it's return a number lower than 1 and moment rounded it at 0.
You can change your code in that without use Date in the moment declaration:
const a = moment('2021-10-31');
const b = moment('2021-11-01');
console.log(a.diff(b, 'days')); // -1
console.log(a.diff(b, 'hours')); // -25 <- but this is wrong
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Or in alternative you can force that .diff() function returns a floating instead of integer putting the third parameter, and after round it like that:
const a = moment(new Date('2021-10-31'));
const b = moment(new Date('2021-11-01'));
console.log(Math.round(a.diff(b, 'days', true)));
console.log(Math.round(a.diff(b, 'hours', true)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Else is to force moment to use the utc date:
const a = moment.utc(new Date('2021-10-31'));
const b = moment.utc(new Date('2021-11-01'));
console.log(a.diff(b, 'days'));
console.log(a.diff(b, 'hours'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

How do I show time in ASP.NET?

I have a label in my asp.net web site that will shows the time. I want the output like here. in the morning like this: 08:26 and after 12 am,it shows 15:28
My code does not work. It only supports the first part.
DateTime tim = DateTime.Now;
int hh = p.GetHour(tim);
int mm = p.GetMinute(tim);
Label7.Text = DateTime.Now.ToString("hh:mm");
According to the Custom date and time format strings docs page - you can see:
"hh" The hour, using a 12-hour clock from 01 to 12.
"HH" The hour, using a 24-hour clock from 00 to 23.
So in your case - just use the capitalized HH for your formatting:
Label7.Text = DateTime.Now.ToString("HH:mm");
and you should get what you're looking for.

MomentJS comparing Unix time with minutes and get difference

I need to find if currentDate time (unix) and lastFetchedTime(unix) is greater than 30 minutes in moment.js.
How can compare the subtracted value from 30 minutes in moment?
lastFetchedTime(unix) is equivalent to the previous Date.now()..
const now = moment(Date.now());
const lastFetched = 1598578706;
const checkTime = now.diff(lastFetched, 'minutes') > 30 ;
You can use momentJS duration function to get the difference between two times which are in unix format.
Firstly, you need to convert the unix format to human readable time and then get the difference of current time and lastFetched time using asMinutes function of duration
If the difference is greater then 30 then do something else or do something else.
Live Demo:
const now = moment().unix()
const lastFetched = 1598597404;
const duration = moment.duration(moment.unix(now).diff(moment.unix(lastFetched)));
const getMinutes = duration.asMinutes();
if (getMinutes > 30) {
console.log('Minutes are GREATER then 30 minutes - from now')
} else {
console.log('Minutes are LESS then 30 minutes - from now')
}
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.js"></script>

Adobe flex dateField

I have some code as follows:
private function onComboChange(evt:Event):void {
var temp:Date = df_date.selectedDate;
temp.date += 5;
df_dateDue.selectedDate = new Date(temp);
}
In essence, I am trying to add 5 days onto the selected date in df_date, and put that date into df_dateDue. This fires off via an EventListener on a combobox. Both df_date and df_dateDue are dateFields.
OK, so the first time that I run this, it works fine; df_date stays the same and df_dateDue is set to 5 days past df_date. However, the next time that I run it, df_dateDue increments by 10 days from df_date, the next time by 15, and so on.
So, stepping through the code shows that somehow df_date has become linked to the temp var, and that the temp var is not resetting itself each time the function is called.
Example: df_date = 01 Jan, df_dateDue = 01 Jan.
Fire off the event, df_date = 01 Jan, df_dateDue = 06 Jan
Fire off the event again. At this point, var temp = 06 Jan (even though df_date still shows 01 Jan), and df_dateDue is then set to 11 Jan
Fire off the event again. At this point var temp = 11 Jan (even though df_date = 01 Jan), and df_dateDue is then set to 16 Jan
What am I missing here?
In Flex/AS, variables that contain objects are really just pointers to some memory space. Date's in Flex are an Object, not a native type. This line:
var temp:Date = df_date.selectedDate;
Creates a new pointer to an existing date object. It does not create a copy.
This line:
temp.date += 5;
increments the date property of the dateObject. All references pointing to that date object will be updated. Try using objectUtil.copy
var temp:Date = ObjectUtil.copy(df_date.selectedDate) as Date;
Oh, and get your acceptance rate up.

Convert 12-hour date/time to 24-hour date/time

I have a tab delimited file where each record has a timestamp field in 12-hour format:
mm/dd/yyyy hh:mm:ss [AM|PM].
I need to quickly convert these fields to 24-hour time:
mm/dd/yyyy HH:mm:ss.
What would be the best way to do this? I'm running on a Windows platform, but I have access to sed, awk, perl, python, and tcl in addition to the usual Windows tools.
Using Perl and hand-crafted regexes instead of facilities like strptime:
#!/bin/perl -w
while (<>)
{
# for date times that don't use leading zeroes, use this regex instead:
# (?:\d{1,2}/\d{1,2}/\d{4} )(\d{1,2})(?::\d\d:\d\d) (AM|PM)
while (m%(?:\d\d/\d\d/\d{4} )(\d\d)(?::\d\d:\d\d) (AM|PM)%)
{
my $hh = $1;
$hh -= 12 if ($2 eq 'AM' && $hh == 12);
$hh += 12 if ($2 eq 'PM' && $hh != 12);
$hh = sprintf "%02d", $hh;
# for date times that don't use leading zeroes, use this regex instead:
# (\d{1,2}/\d{1,2}/\d{4} )(\d{1,2})(:\d\d:\d\d) (?:AM|PM)
s%(\d\d/\d\d/\d{4} )(\d\d)(:\d\d:\d\d) (?:AM|PM)%$1$hh$3%;
}
print;
}
That's very fussy - but also converts possibly multiple timestamps per line.
Note that the transformation for AM/PM to 24-hour is not trivial.
12:01 AM --> 00:01
12:01 PM --> 12:01
01:30 AM --> 01:30
01:30 PM --> 13:30
Now tested:
perl ampm-24hr.pl <<!
12/24/2005 12:01:00 AM
09/22/1999 12:00:00 PM
12/12/2005 01:15:00 PM
01/01/2009 01:56:45 AM
12/30/2009 10:00:00 PM
12/30/2009 10:00:00 AM
!
12/24/2005 00:01:00
09/22/1999 12:00:00
12/12/2005 13:15:00
01/01/2009 01:56:45
12/30/2009 22:00:00
12/30/2009 10:00:00
Added:
In What is a Simple Way to Convert Between an AM/PM Time and 24 hour Time in JavaScript, an alternative algorithm is provided for the conversion:
$hh = ($1 % 12) + (($2 eq 'AM') ? 0 : 12);
Just one test...probably neater.
It is a 1-line thing in python:
time.strftime('%H:%M:%S', time.strptime(x, '%I:%M %p'))
Example:
>>> time.strftime('%H:%M:%S', time.strptime('08:01 AM', '%I:%M %p'))
'08:01:00'
>>> time.strftime('%H:%M:%S', time.strptime('12:01 AM', '%I:%M %p'))
'00:01:00'
Use Pythons datetime module someway like this:
import datetime
infile = open('input.txt')
outfile = open('output.txt', 'w')
for line in infile.readlines():
d = datetime.strptime(line, "input format string")
outfile.write(d.strftime("output format string")
Untested code with no error checking. Also it reads the entire input file in memory before starting.
(I know there is plenty of room for improvements like with statement...I make this a community wiki entry if anyone likes to add something)
To just convert the hour field, in python:
def to12(hour24):
return (hour24 % 12) if (hour24 % 12) > 0 else 12
def IsPM(hour24):
return hour24 > 11
def to24(hour12, isPm):
return (hour12 % 12) + (12 if isPm else 0)
def IsPmString(pm):
return "PM" if pm else "AM"
def TestTo12():
for x in range(24):
print x, to12(x), IsPmString(IsPM(x))
def TestTo24():
for pm in [False, True]:
print 12, IsPmString(pm), to24(12, pm)
for x in range(1, 12):
print x, IsPmString(pm), to24(x, pm)
This might be too simple thinking, but why not import it into excel, select the entire column and change the date format, then re-export as a tab delimited file? (I didn't test this, but it somehow sounds logical to me :)
Here i have converted 24 Hour system to 12 Hour system.
Try to use this method for your problem.
DateFormat fmt = new SimpleDateFormat("yyyyMMddHHssmm");
try {
Date date =fmt.parse("20090310232344");
System.out.println(date.toString());
fmt = new SimpleDateFormat("dd-MMMM-yyyy hh:mm:ss a ");
String dateInString = fmt.format(date);
System.out.println(dateInString);
} catch (Exception e) {
System.out.println(e.getMessage());
}
RESULT:
Tue Mar 10 23:44:23 IST 2009
10-March-2009 11:44:23 PM
In Python: Converting 12hr time to 24hr time
import re
time1=input().strip().split(':')
m=re.search('(..)(..)',time1[2])
sec=m.group(1)
tz=m.group(2)
if(tz='PM'):
time[0]=int(time1[0])+12
if(time1[0]=24):
time1[0]-=12
time[2]=sec
else:
if(int(time1[0])=12):
time1[0]-=12
time[2]=sec
print(time1[0]+':'+time1[1]+':'+time1[2])
Since you have multiple languages, I'll suggest the following algorithm.
1 Check the timestamp for the existence of the "PM" string.
2a If PM does not exist, simply convert the timestamp to the datetime object and proceed.
2b If PM does exist, convert the timestamp to the datetime object, add 12 hours, and proceed.

Resources