Convert epoch difference to number of days - perl

I computed the difference of two ISO 8601 dates after coverting them to epoch.
How can I get the difference of them in number of days?
My code is
my $ResolvedDate = "2014-06-04T10:48:07.124Z";
my $currentDate = "2014-06-04T06:03:36-04:00"
my $resolved_epoch = &convert_time_epoch($ResolvedDate);
my $current_epoch = &convert_time_epoch($currentDate);
if (($resolvedDate - $currentDate) > $noOfDays) {
print "Difference in greater than x\n";
$built = 0;
return ($built);
} else {
print "Difference in smaller than x \n";
$built = 1;
return ($built);
}
sub convert_time_epoch {
my $time_c = str2time(#_);
my #time_l = localtime($time_c);
my $epoch = strftime("%s", #time_l);
return($epoch);
}
Here in addition to $built I also want to return exact number of days, Resolved date is greater than Current date.

"number of days" is awkward, because this is localtime and DST exists (or at least, may exist).
By simply dividing by 86400 you can easily obtain the number of 24-hour periods, which may be sufficient for your purposes.
If you want the true number of times that the mday field has changed, this may be slightly different from the value obtained by this simple division, however.

If the dates are in epoch seconds, take the difference and divide it by the number of seconds in a day (which is 86400). Like so:
my $days_difference = int(($time1 - $time2) / 86400);
If you use DateTime then
my $duration = $dt1->delta_days($dt2); #$dt1 and $dt2 are DateTime objects.
print $duration->days;

use DateTime::Format::ISO8601 qw( );
my $ResolvedDate = "2014-06-04T10:48:07.124Z";
my $currentDate = "2014-06-04T06:03:36-04:00";
my $format = DateTime::Format::ISO8601->new();
my $dt_resolved = $format->parse_datetime($ResolvedDate);
my $dt_current = $format->parse_datetime($currentDate);
my $dur = $dt_resolved->delta_days($dt_current);
my $days = $dur->in_units('days');

Related

How to calculate hour to day in NetCDf file using scala

is there a method to convert the unit from hours to days in this dataset ?
double time(time) ;
time:units = "hours since 1800-01-01 00:00:0.0" ;
time:long_name = "Time" ;
time:delta_t = "0000-01-00 00:00:00" ;
time:avg_period = "0000-01-00 00:00:00" ;
time:standard_name = "time" ;
time:axis = "T" ;
time:actual_range = 1569072., 1895592. ;
If you can use Python, it's an easy process:
The first step is to convert the numeric dates to a datetime object using netCDF4 num2date.
The second step is to compute the number of days between each datetime object and the time stamp (or original date) in the time variable (i.e. 1800-01-01).
import netCDF4
import datetime
ncfile = netCDF4.Dataset('./precip.mon.mean.nc', 'r')
time = ncfile.variables['time']
# Convert from numeric times to datetime objects
dates = netCDF4.num2date(time[:], time.units)
# Compute number of days since the original date
orig_date = datetime.datetime(1800,1,1)
days_since = [(t - orig_date).days for t in dates]

Get Every Tuesday of the month with Coldfusion

I'm currently working with jquery FullCalendar plugin to create a specific calendar.
One of my tasks I have to work out is how to get any given specific day for the month.
I'm currently using Coldfusion 10 for the server side so I'm wondering is there any specific way of getting every instance of a Tuesday into an array of dates?
Ideally I would like to do this on the server side and populate the calendar plugin.
My issue is primarily trying to source every specific day of a calendar month.
Any advice greatly appreciated.
The firstXDayOfMonth() UDF on CFLlib allows you to find the first of a given day-of-week in a given month. From there you just need to loop from that date adding 7 each iteration until the month is no long the selected month.
theMonth = month(now());
startDate = firstXDayOfMonth(3, theMonth, year(now()));
tuesdays = [];
for (date=startDate; month(date) == theMonth; date +=7){
arrayAppend(tuesdays, dateAdd("s",0, date)); // this just converts date from a number back to a date
}
writeDump(tuesdays);
Update:
Actually the approach for that UDF on CFLib is terrible. Use this variation instead:
function firstXDayOfMonth(dayOfWeek,month,year){
var firstOfMonth = createDate(year, month,1);
var dowOfFirst = dayOfWeek(firstOfMonth);
var daysToAdd = (7 - (dowOfFirst - dayOfWeek)) MOD 7;
var dow = dateAdd("d", daysToAdd, firstOfMonth);
return dow;
}
I'll update the UDF on cflib a bit later: I need to write some decent unit tests for it first, and am a bit busy # the moment.
The Short Version:
At this time, there is not a function in CF that gets all the Tuesdays. But here's an easy way to do it:
// assuming a year and month are defined already
var firstDayOfMonth = createDate( year, month, 1 );
var targetDayOfWeek = 3; // Tuesday is 3 if Sunday is 1
var dayOfWeekArray = []; // This is the outcome.
// loop through each day of the month adding the target days to the array.
for( i = 1; i LTE daysInMonth( firstDayOfMonth ); i++){
var loopingDate = createDate( year, month, i );
if( dayOfWeek( loopingDate ) == targetDayOfWeek ){
ArrayAppend( dayOfWeekArray, loopingDate );
}
}
dayOfWeekArray is an array of every Tuesday of a month.
More Detail:
Your title and post seem to conflict as far as what you're looking for, so I'm going to stick with the title, since that's why I came here...
Here's what you can do to find all the Tuesdays in a month:
Create a date Object
Loop through the days in the target month using the date Object
If the current day is Tuesday, add it to an array
Boom, you got all the Tuesdays of a month in an array
Here's the code I used (cfscript):
// assuming a year and month are defined already
var firstDayOfMonth = createDate( year, month, 1 );
var dayOfWeekArray = [];
var targetDayOfWeek = 3; // Tuesday is 3 if Sunday is 1. Do a quick writeDump in the loop if you're not sure.
for( i = 1; i LTE daysInMonth( firstDayOfMonth ); i++){
var loopingDate = createDate( year, month, i );
if( dayOfWeek( loopingDate ) == targetDayOfWeek ){
ArrayAppend( dayOfWeekArray, datePart( "d", loopingDate );
// ArrayAppend( dayOfWeekArray, loopingDate ); - use this if you'd rather have the whole date object
}
}
This gives you dayOfWeekArray which will be the date of each Tuesday of a particular month. For instance, this month (Jan 2019) will be [1, 8, 15, 22, 29]. You can change this to be the entire date object if you want - that's what I did in the short version at the top.

Converting numbers to K/M/G/T and days/hours/min?

Is there an easy way to convert numbers like these
123 -> 123B
1234 -> 1.2K
12345 -> 12.2K
123456 -> 123.4K
1234567 -> 1.2M
12345678 -> 12.3M
123456789 -> 123.4M
...
and ideally also large numbers into days/hours/min. ?
This was discussed on Stackoverflow using Time::Piece. One of the answers comes close to calculating days hours minutes. From what I've read about this question before, I think you can easily code it up like this:
sub dhms {
my $seconds = shift;
my $days = int $seconds / 86400;
$seconds %= 86400;
my $hours = int $seconds / 3600;
$seconds %= 3600;
my $mins = int $seconds / 60;
my $secs = $seconds % 60;
return $days, $hours, $mins, $secs;
}
Update: daxim's answer using DateTime::Format::Duration does this as well
Suffixing is quite simple actually, once we understand the relationship between the letters K, M, G, T and the factors they present:
K = 10^3 = 10^3^1
M = 10^6 = 10^3^2
G = 10^9 = 10^3^3
T = 10^12 = 10^3^4
The next important thing to realize is that 10^0 = 1.
We want to select the largest suffix whose value is smaller than the value we want to transform. To do that, we put the suffixes into an array:
my #suffixes = qw/ B K M G T /;
so that
$suffixes[$i] == 10**3**$i # conceptually
Now it's just a matter of looping over the indices (probably in reverse) and stopping as soon as the $val >= 10**3**$i.

Getting The End Date of the Given Month

I need to get the end date of the given month for some calculation purpose,
how can I do that in PHP, I tried using date() function, but It didn't work.
I used this:
date($year.'-'.$month.'-t');
But this gives the current month's end date.
I think I'm wrong somewhere, I couldn't find where I'm going wrong here.
If I give year as 2012 & month as 03, then it must show me as 2012-03-31.
This code will give you last day for a specific month.
$datetocheck = "2012-03-01";
$lastday = date('t',strtotime($datetocheck));
You want to replace your date() call with:
date('Y-m-t', strtotime($year.'-'.$month.'-01'));
The first parameter to date() is the format you want to be returned, and the second parameter has to be a unix timestamp (or not passed to use the current timestamp). In your case, you can generate a timestamp with the function strtotime(), passing it a date string with the year, the month, and 01 for the day. It will return that same year and month, but the -t in the format will be replaced by the last day of the month.
If you want to return only the last day of the month without year and month:
date('t', strtotime($year.'-'.$month.'-01'));
Just use 't' as your format string.
Current month:
echo date('Y-m-t');
Any month:
echo date('Y-m-t', strtotime("$year-$month-1"));
Try below code.
$m = '03';//
$y = '2012'; //
$first_date = date('Y-m-d',mktime(0, 0, 0, $m , 1, $y));
$last_day = date('t',strtotime($first_date));
$last_date = date('Y-m-d',mktime(0, 0, 0, $m ,$last_day, $y));
function lastday($month = '', $year = '') {
if (empty($month)) {
$month = date('m');
}
if (empty($year)) {
$year = date('Y');
}
$result = strtotime("{$year}-{$month}-01");
$result = strtotime('-1 second', strtotime('+1 month', $result));
return date('Y-m-d', $result);
}
function firstOfMonth() {
return date("Y-m-d", strtotime(date('m').'/01/'.date('Y').' 00:00:00')). 'T00:00:00';}
function lastOfMonth() {
return date("Y-m-d", strtotime('-1 second',strtotime('+1 month',strtotime(date('m').'/01/'.date('Y').' 00:00:00')))). 'T23:59:59';}
$date1 = firstOfMonth();
$date2 = lastOfMonth();
try this ,this give you a current month's starting and ending date.
date("Y-m-d",strtotime("-1 day" ,strtotime("+1 month",strtotime(date("m")."-01-".date("Y")))));
function getEndDate($year, $month)
{
$day = array(1=>31,2=>28,3=>31,4=>30,5=>31,6=>30,7=>31,8=>31,9=>30,10=>31,11=>30,12=>31);
if($year%100 == 0)
{
if($year%400 == 0)
$day[$month] = 29;
}
else if($year%4 == 0)
$day[$month] = 29;
return "{$year}-{$month}-{$day[$month]}";
}
If you are using PHP >= 5.2 I strongly suggest you use the new DateTime object. For example like below:
$a_date = "2012-03-23";
$date = new DateTime($a_date);
$date->modify('last day of this month');
echo $date->format('Y-m-d');

Formatting Date::Manip's Delta to days

I have this routine,
I want to save that delta to count the days between all to and from days in the from-to pairs
I have in the 2 dimensional array, I just need the workdays.
Say for
$date_from = 2012-02-09;
$date_to = 2012-02-13;
$delta_string = 4
sub calc_usage {
use Date::Manip::Date;
my $date_from;
my $date_to;
my $delta;
my $i;
for $i (0 .. $#DATE_HOLDER) {
$date_from = new Date::Manip::Date;
$date_to = new Date::Manip::Date;
$date_from->parse($DATE_HOLDER[$i][0]);
$date_to->parse($DATE_HOLDER[$i][1]);
$delta = $date_from->calc($date_to, "business");
}
}
To retrieve the delta values, you have to use the folllowing:
my #val = $delta->value();
wich gives an array of 7 elements where:
$val[0] holds years
$val[1] holds months
$val[2] holds weeks
$val[3] holds days
$val[4] holds hours
$val[5] holds minutes
$val[6] holds seconds
you can also use it in scalar context:
my $val = $delta->value();
wich gives a string with the same 7 elements colon separated:
years:months:weeks:days:hours:minutes:seconds