Operation with dates with format ISO 8601? - date

I need to make an PHP operation with dates with format ISO 8601. Something like:
$starDate = 2012-03-20T00:00:00+01:00; //20 March 2012
$endDate = 2012-04-01T00:00:00+02:00; // 1 April 2012
$diff = $starDate - $endDate; //Result should be: 13
Using this code $diff get a value of cero.

Try this :
function date_diff($date1, $date2)
{
$s = strtotime($date2)-strtotime($date1);
$d = intval($s/86400)+1;
return "$d";
}
Source : http://forum.hardware.fr/hfr/Programmation/PHP/php-calculer-nombre-sujet_30415_1.htm

Related

Get Lotus Notes calendar entries for a time range in powershell

I try to track the time I use for projects by adding the project id as a category to a lotus notes calendar entry.
Now I want to select all appointments over a time range (i.e. the last 7 days), group them by category and sum up the time.
Except for the time range thingy it works fine. The solution seams to be the method GetAllDocumentsByKey (https://help.hcltechsw.com/dom_designer/9.0.1/appdev/H_GETALLDOCUMENTSBYKEY_METHOD.html)
I tried to define a time range, a string (subject or category) or an array (values: subject or category) as keyArray but nothing seams to work.
Any idea?
$notesINI = Get-IniContent $env:LOCALAPPDATA\IBM\Notes\Data\notes.ini
$InputNotesMailBox = $notesINI.Notes.MailFile
$InputNotesServer = $notesINI.Notes.MailServer
$DomSession = New-Object -ComObject Lotus.NotesSession
$DomSession.Initialize()
$DomDatabase = $DomSession.GetDatabase($InputNotesServer,$InputNotesMailBox)
$DomView = $DomDatabase.GetView('Calendar')
# This works fine but is really slow because it processes all the documents in my calendar (5Min for 6k documents)
$DomDocRange = $DomView
$DomDoc = $DomDocRange.GetFirstDocument()
$date_s = $(get-date -Year 2022 -Month 4 -Day 7)
$date_e = $(get-date -Year 2022 -Month 4 -Day 14)
while($DomDoc -ne $null){
if($DocCategory -like "proiject-*"){
$Termin_StartDate = $DomDoc.getItemVAlue('StartDateTime')[0]
if(IsBetweenDates2 $date_s $date_e $(get-date $Termin_StartDate)){
# add time and project id to multidimensional array
}
}
}
# does not work because I don't know how to filter getAllDocumentsByKey
$date_s = $(get-date -Year 2022 -Month 4 -Day 7)
$date_e = $(get-date -Year 2022 -Month 4 -Day 14)
$DomDateRange = $DomSession.CreateDateRange()
$DomDateRange.StartDateTime = $DomSession.CreateDateTime($date_s)
$DomDateRange.EndDateTime = $DomSession.CreateDateTime($date_e)
$DomDocRange = $DomView.getAllDocumentsByKey($DomDateRange, $true)
$DomDoc = $DomDocRange.GetFirstDocument()
while($DomDoc -ne $null){
if($DocCategory -like "proiject-*"){
$Termin_StartDate = $DomDoc.getItemVAlue('StartDateTime')[0]
if(IsBetweenDates2 $date_s $date_e $(get-date $Termin_StartDate)){
# add time and project id to multidimensional array
}
}
}
GetDocumentByKey is a function of a view that needs to be sorted by the key you are searching for. The "Calendar"- view is not suitable for this function.
You need to get away from NotesView and get your document collection from the database itself without using the view.
$DomDocRange = $DomDatabase.search( 'Form = "Appointment" & StartDateTime >= [InjectYourStartDateHere] & StartDateTime <= [InjectYourEndDateHere]', Nothing, 0 )
$DomDoc = $DomDocRange.GetFirstDocument()
The constructed #Formula needs to look like this in the end:
Form = "Appointment" & StartDateTime >= [04/01/2022] & StartDateTime <= [04/12/2022]
The brackets are important as they mark the given value as a date. The date needs to be in your local format (MM/DD/YYYY or DD.MM.YYYY or...).
Unfortunately I did not use the interface with Powershell yet, so I can't tell you, how the insert the LotusScript variable "Nothing" here, you could try omit it (use double comma) or use $null...

Trouble with converting to Datetime object

I have the below data which is an object type variable named $timestamps
Sat Jan 15 16:21:24
Sat Jan 15 01:31:22
Fri Jan 14 20:58:09
Fri Jan 14 20:51:02
I'm having trouble converting it to Datetime object because of the weird date format. How would you handle this?
I would like it as a datetime object because I plan to convert from current (UTC) to EST.
TIA
You can use the the ParseExact() method provided by the [datetime] class for this:
[datetime]::ParseExact('Fri Jan 14 20:58:09','ddd MMM dd HH:mm:ss',$null)
# returns a - datetime - object of:
# Friday, January 14, 2022 8:58:09 PM
dd - for the day.
MM - for the month.
HH - for the hour - Capitalized for the 24 hour time format.
mm - for the minutes.
ss - for the seconds.
Edit: as suggested by mklement0, we can use [cultureinfo]::InvariantCulture to make the parsing specific to an English date time format. Also, changing dd to d as a more robust solution for days without 2 digits; which should cover both singular, and double digit days.
Seeing $timestamps is an array of strings, you can use a loop (of your choice - in this case the Foreach-Object cmdlet) to iterate through each string parsing the text to return a datetime object:
$timestamps | ForEach-Object {
$culture = [cultureinfo]::InvariantCulture
$format = 'ddd MMM d HH:mm:ss'
$date = [datetime]::ParseExact($_,$format,$culture,'AssumeUniversal, AdjustToUniversal')
[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId($date, 'Eastern Standard Time')
}
Using 'AssumeUniversal, AdjustToUniversal' ensures a UTC output.
Assuming from your comment that you'd like to do a conversion to Eastern Time, passing the newly created datetime object to [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId() with an argument of the desired time zone, you can get your result in the new time zone.
When using $null, the CultureInfo object that corresponds to the current culture is used.
The DateTime.ParseExact() method is probably what you're looking for.
PS C:\TEMP>$timestamp = 'Sat Jan 15 16:21:24'
PS C:\TEMP>$format = 'ddd MMM dd HH:mm:ss'
PS C:\TEMP>[datetime]::ParseExact($timestamp, $format, $null)
Saturday, January 15, 2022 04:21:24 PM
PS C:\TEMP>

PowerShell Print this business weeks mon-fri

I would like Powershell to determine the current week & print monday - friday in the format:
mm/dd/yyyy - mm/dd/yyyy
I saw a way to get the day of the week which is nice but I would like to just have it show the dates.
What I have so far, it works but if I run any day but Monday the dates would be off:
$bar = "------------------------------------"
$today = (Get-Date)
$dates = #($today.AddDays(0).ToString('MM-dd-yyyy'),
$today.AddDays(1).ToString('MM-dd-yyyy'),
$today.AddDays(2).ToString('MM-dd-yyyy'),
$today.AddDays(3).ToString('MM-dd-yyyy'),
$today.AddDays(4).ToString('MM-dd-yyyy'))
$result = "`n{0}`n{1}`n`n`n{2}`n{3}`n`n`n{4}`n{5}`n`n`n{6}`n{7}`n`n`n{8}`n{9}`n" -f $dates[0], $bar, $dates[1], $bar, $dates[2], $bar, $dates[3], $bar, $dates[4], $bar
echo $result
this seems to do what you want. [grin] it uses the builtin weekday list, indexes into that with the current weekday name, calculates the 1st day of the current week, generates an array of dates for the current week, and finally prints it out with the lines & vertical spacing that you seem to want.
# for my locale, the 1st day is "Sunday"
$WeekDayList = [System.DayOfWeek].GetEnumNames()
$Line = '-' * 40
$Newline = [environment]::NewLine
$BlankLineCount = 3
# the ".Date" property gives you midnite, not "now"
$Today = (Get-Date).Date
$TodayNumber = $WeekDayList.IndexOf($Today.DayOfWeek.ToString())
$WeekStartDate = $Today.AddDays(-$TodayNumber)
$CurrentWeek = foreach ($Offset in 0..6)
{
$WeekStartDate.AddDays($Offset).ToString('yyyy-MM-dd')
}
-join ($CurrentWeek -join "$Newline$Line$($Newline * $BlankLineCount)"), "$Line$($Newline * $BlankLineCount)"
output ...
2019-01-20
----------------------------------------
2019-01-21
----------------------------------------
2019-01-22
----------------------------------------
2019-01-23
----------------------------------------
2019-01-24
----------------------------------------
2019-01-25
----------------------------------------
2019-01-26
----------------------------------------
[not part of the output - needed to show that there are two blank lines above this one. [*grin*]
I have come across the requirement to get a date from a week day, and wrote a function to return a [DateTime].
Using this function and ToString() to format the date to your requirements, gives an output of:
2019/01/21 - 2019/01/25
Code:
Function Get-DateFromDay {
param(
[Parameter(Mandatory = $true)]
[ValidateSet('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')]
[string]$WeekDay,
[Int]$AddWeeks = 0
)
$DayNumber = #{
'Saturday' = 1;
'Sunday' = 0;
'Monday' = -1;
'Tuesday' = -2;
'Wednesday' = -3;
'Thursday' = -4
'Friday' = -5
}
[System.Datetime]$Today = Get-Date
$NumDaysSinceDateFromDay = $Today.DayOfWeek.value__ + $DayNumber[$WeekDay]
[System.Datetime]$DateFromDayThisWeek = $Today.AddDays(-$NumDaysSinceDateFromDay)
$DateFromDayThisWeek.AddDays( + ($AddWeeks * 7))
}
$Monday = (Get-DateFromDay -WeekDay Monday).ToString('yyyy/MM/dd')
$Friday = (Get-DateFromDay -WeekDay Friday).ToString('yyyy/MM/dd')
Write-Output "$Monday - $Friday"
And a few examples of use for those who come across this post in the future:
Thursday next week:
Get-DateFromDay -WeekDay Thursday -AddWeeks 1
Tuesday last week:
Get-DateFromDay -WeekDay Tuesday -AddWeeks -1

to find date difference in mongodb query in codeigniter

I want to get difference between a date that I found from the database and the other is the current date both are in the same format(example - 2018-06-09 11:02:49).
How can I find the difference between two dates in days format in CodeIgniter?
Try this
$date1 = date_create("2018-06-09 11:02:49");
$date2 = date_create("2018-06-08 11:02:49");
$diff = date_diff($date1, $date2);
echo $diff->format("%a day");
Hope this will help you :
First way : you can use CI date_helper's timespan method
$expired_date = '2018-06-09 11:02:49';
$post_date = strtotime($expired_date);
$now = time();
$units =1;
echo timespan($post_date, $now, $units);
Ouptput :
2 Days
Second way use core php date_diff() method
working demo : https://eval.in/1018721
//$expired_date = $query->row()->expired_at;
$expired_date = '2018-06-09 11:02:49';
$expired_date = date_create($expired_date);
$cdate = date_create('now');
$interval = date_diff($expired_date,$cdate);
//echo $interval->format('%a').PHP_EOL;
echo $interval->d;
Output :
2
CI reference : https://www.codeigniter.com/user_guide/helpers/date_helper.html
For more : http://php.net/manual/en/function.date-diff.php
If you're using PHP 5.3 >, this is by far the most accurate way of calculating the difference:
$earlier = new DateTime("2018-05-20 11:02:49");
$later = new DateTime("2018-06-11 11:02:49");
$diff = $later->diff($earlier)->format("%a day(s)");

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');