CakePHP 3 - Comparing and modifying dates - date

In the CakePHP 3 Cookbook on Date/Time, you can compare time intervals with future/past days/weeks using IsWithinNext/WasWithinNext. You can also modify dates/times by doing a ->modify('extra time') - eg. if $date = 2016-01-01, $date->modify('+1 week') would mean $date = 2016-01-08.
These features require the use of Cake\i18n\Time. However, when I attempted to use these features, I received a Cake error:
Call to a member function isWithinNext() on string.
This is the code I used:
$date_start = \Cake\Database\Type::build('date')->marshal($data['session']['date_start'])->i18nFormat(); //before hand my dates were in the form of an array comprised of Year, Month and Day. This changes them into date format.
if($date_start->isWithinNext('1 week')){
$deposit_due = $booking->date_confirm;
$deposit_due->modify('+48 hours');
} elseif ($date_start->isWithinNext('2 weeks')){
$deposit_due = $booking->date_confirm;
$deposit_due->modify('+1 week');
} elseif ($date_start->isWithinNext('3 weeks')){
$deposit_due = $booking->date_confirm;
$deposit_due->modify('+1 week');
} else {
$deposit_due = $booking->date_confirm;
$deposit_due->modify('+2 weeks');
}

Calling i18nFormat() returns a formatted string as you can look up in the API: https://api.cakephp.org/3.4/class-Cake.I18n.DateFormatTrait.html#_i18nFormat
This, for example, should work:
$date_start = new \Cake\I18n\Time($data['session']['date_start']);
debug($date_start->isWithinNext('2 weeks'));

Related

Comparing date by combining it

Im just wondering. is it ok to combine years,month, and day of two date and make a comparison based on the combination.
eg:
Date A: 12th-January-2019
Date B: 24th-December-2018
Based on the above date, i could combine the year,month, and day as follow:
Date A: 20190112
Date B: 20181224
So based on the numbers, i could do logic like below to compare which date comes first:
if(Date A > Date B) {
output("Date A is the latest")
}
i would like to implement this method just to compare which is the latest date.
are there any problem of doing so.
java.time
Since you are using Java, I suggest that you take advantage of java.time, the modern Java date and time API.
String[] dateStringsFromDatabase = {
"2018/12/19",
"2017-02-01",
"2018.03.04",
"25-12-2016", // reversed
"2019\\09\\12",
"2014:03:01"
};
List<LocalDate> parsedDates = new ArrayList<>(dateStringsFromDatabase.length);
for (String dateString : dateStringsFromDatabase) {
// No matter which delimiter is used, replace it with a hyphen
String text = dateString.replaceAll("\\W", "-");
try {
parsedDates.add(LocalDate.parse(text));
} catch (DateTimeParseException dtpe) {
System.out.println(dateString + " not parsed: " + dtpe.getMessage());
}
}
Output:
25-12-2016 not parsed: Text '25-12-2016' could not be parsed at index 0
What this approach buys you is validation of the dates even though they come with all different delimiters. Especially in this situation I believe that you should want to validate that your strings are within the expected variations. Otherwise you risk that a date with the numbers reversed ends up as a date in year 2512, for example. You want to catch that before it happens.
Example of comparing which comes first:
for (int i = 1; i < parsedDates.size(); i++) {
LocalDate dateA = parsedDates.get(i - 1);
LocalDate dateB = parsedDates.get(i);
if (dateA.isAfter(dateB)) {
System.out.format("%s is later than %s%n", dateA, dateB);
}
}
Output:
2018-12-19 is later than 2017-02-01
2019-09-12 is later than 2014-03-01
Link: Oracle tutorial: Date Time explaining how to use java.time.

Formatting a Time value on Ionic 3

I need to find the way to format a time, I tried with angular pipe, but this works with date type values.
I need to be able to remove the seconds to values of the hours shown, example:
1:45:00 change to 1:45 pm or 1:45 p.m. M.
Assuming your date is a instance of Date you can use the built in angular date pipe with the predefined format shortTime or a custom format:
<p> {{date | date:'shortTime'}} </p>
<p> {{date | date:'hh:mm'}} </p>
shortTime is equivalent to 'h:mm a' and will produce results like 9:03 AM.
The custom format 'hh:mm' will produce results like 09:03.
If your date is just a string you could use the built in slice pipe to remove the parts you want to get rid of:
<p> {{"1:45:00" | slice:0:4}} </p>
Which will output 1:45.
Also see this Stackblitz for the different options.
Anyway I'd reccomend using real Date objects or Moment.js objects over bare strings, it makes things a lot easier, especially once you start comparing dates or calculating with dates.
Use Moment.js .here you can convert to any time format
1 - Install via NPM:
npm install moment -S
2 - Import in your Typescript file:
import moment from 'moment';
3 - Use in your Typescript file:
let dateString = "22-04-2017"; //whatever date string u have
let dateObject = moment(dateString, "DD-MM-YYYY").toDate();
If this is format is always the case you can manipulate the string with JavaScript/TypeScript.
myTime = '1:45:00'
showTime() {
var result =
this.myTime.substring(
0, (this.myTime.length - 3) )+ ' pm';
console.log(result);
}
If you have more complicated cases You could use a library like Momentjs.
https://momentjs.com/
This is where you can find what you need in the docs.
https://momentjs.com/docs/#/parsing/string-format/
you can use a custom pipe
transform(timeString: string) {
let time = timeString.slice(0, 5);
let current_hour = timeString.slice(0, 2);
if (parseInt(current_hour) > 12) {
time = time + " PM";
} else {
time = time + " AM";
}
return time;
}

Calculate number of days between two dates in Perl

I am using Perl to create a script that will email password expiration notifications.
I have two dates:
The date that the users password was set
The date that the users password will expire (180 days after the password was set)
use DateTime::Format::Strptime;
my $dt_pattern = DateTime::Format::Strptime->new( pattern => '%F',);
my $displayName = $entry->get_value("displayName");
my $pwdLastSet = convertWinFileTimestamp($entry->get_value("pwdLastSet"));
# Determine password expiration date
my $pwdLastSet_dt = $dt_pattern->parse_datetime($pwdLastSet);
my $pwdExpirationDate = $pwdLastSet_dt->add( days => $maxPwdAge );
# Days until password expires
# HELP!!!!!!!
sub convertWinFileTimestamp {
my $timestamp = shift;
# Strip off nanoseconds, then adjust date from AD epoch (1601) to UNIX epoch (1970)
return POSIX::strftime( "%Y-%m-%d",
localtime( ( $timestamp / 10000000 ) - 11644473600 ) );
}
I cannot figure out how to calculate the difference between the two dates!
Below is the output for each variable:
pwdLastSet: 2015-02-12
pwdExpireDate: 2015-08-11T00:00:00
Any help much appreciated...been googling like crazy but I can't figure it out...Thanks!
I tried the following lines of code:
my $pwdDaysLeft = int(($pwdExpirationDate - $pwdLastSet) / 86400);
but got the following error:
Only a DateTime::Duration or DateTime object can be subtracted from a DateTime object. at pwdreminder.pl line 65
So, we have three dates here:
The date that the password was last set. This starts off as a string in the format YYYY-MM-DD stored in $pwdLastSet, but then you parse it into a DateTime object stored in $pwdLastSet_dt.
The date that the current password expires. This is calculated by adding $maxPwdAge days to $pwdLastSet_dt, which gives a DateTime object which is then stored in $pwdExpirationDate.
The current date. Which, in your current code, you don't calculate.
What you actually want is the difference in days a between the second and third of these two dates. We can ignore the first date as is it only used to calculate the second date. I assume that you're calculating that correctly.
Hopefully, the password expiration date will always be in the future. So the calculation we want to do is:
my $diff = $pwdExpirationDate - $current_date;
As long as both of those are DateTime objects, we'll get a DateTime::Duration object back, which we can then ask for the number of days.
DateTime has a today() method that will give the current date. So our code becomes:
# Use delta_days() to get a duration object that just contains days
my $diff = $pwdExpirationDate->delta_days(DateTime->today);
print $diff->in_units('days');

how to check the date using internet in matlab?

when using date command in matlab, i get the system current date. is there a way to get the current date using internet in matlab? the link i've given is similar to this question but that question was asked for vb, and i'm trying to do this thing in matlab.
https://stackoverflow.com/questions/21198527/how-to-check-the-real-date-time-through-an-internet-connection]
MATLAB Code based on urlread to get current date using internet (URL) and with couple of bounding keys (to find the date string) -
URL = 'http://time.is/';
key1 = 'title="Click for calendar">';
key2 = '</h2>';
data = urlread(URL);
start_ind = strfind(data,key1);
data1 = data(start_ind:end);
off_stop_ind = strfind(data1,key2);
current_date = data(start_ind+ numel(key1):start_ind + off_stop_ind(1)-2)
Output at my location -
current_date =
Saturday, September 6, 2014, week 36
If you would like to have it in the DD-MM-YYYY format, use this -
date_split = strsplit(current_date,',')
current_date1 = datestr(strcat(date_split(2),date_split(3)))
Output -
current_date1 =
06-Sep-2014

What is the most efficient way to convert an eight digit number to a date?

I am using ColdFusion 9.0.1 and some database that I cannot change.
I am accessing a database that stores a date as an eight digit numeric with zero decimal places like this:
YYYYMMDD
I need to be able to read the date, add and subtract days from a date, and create new dates. I am looking for a ColdFusion solution to efficiently (not much code) to convert the date to our standard format, which is
MM/DD/YYYY
And then convert it back into the database's format for saving.
I need to code this in such a way that non-ColdFusion programmers can easily read this and use it, copy and modify it for other functions (such as adding a day to a date). So, I am not looking for the most least amount of code, but efficient and readable code.
Can you suggest anything that would make this code block more flexible, readable, or more efficient (less code)?
<cfscript>
// FORMAT DB DATE FOR BROWSER
DateFromDB = "20111116";
DatedToBrowser = createBrowserDate(DateFromDB);
writeOutput(DatedToBrowser);
function createBrowserDate(ThisDate) {
ThisYear = left(ThisDate, 4);
ThisMonth = mid(ThisDate, 4, 2);
ThisDay = right(ThisDate, 2);
NewDate = createDate(ThisYear, ThisMonth, ThisDay);
NewDate = dateFormat(NewDate, "MM/DD/YYYY");
return NewDate;
}
// FORMAT BROWSER DATE FOR DB
DateFromBrowser = "11/16/2011";
DateToDB = createDBDate(DateFromBrowser);
writeDump(DateToDB);
function createDBDate(ThisDate) {
ThisYear = year(ThisDate);
ThisMonth = month(ThisDate);
ThisDay = day(ThisDate);
NewDate = "#ThisYear##ThisMonth##ThisDay#";
return NewDate;
}
</cfscript>
First find who ever did the database and kick them in the nads...
Personally I'd Convert with sql so my code only dealt with date objects.
Select Convert(DateTime, Convert(VarChar(8),DateTimeInventedByIdjitColumn))
From SomeTable
As stated by our peers, store dates as dates.
'08/06/2011' could be 8th of june of the 6th of August depending on locale.
20111643 is a valid integer..
Not using a proper date type is just a massive collection of features and bugs that at best are waiting to happen.
You can actually rewrite each function into 1 line of code.
function createBrowserDate(ThisDate) {
return mid(ThisDate,4,2) & "/" & right(ThisDate,2) & "/" & left(ThisDate,4);
}
and
function createDBDate(ThisDate) {
return dateFormat( ThisDate, "YYYYMMDD" );
}
Don't keep dates as strings - keep dates as dates and format them when you need to.
If you can't correct the database to use actual date columns (which you should if you can), then you can use these two functions to convert to/from YYYYMMDD and a date object:
function parseYMD( YYYYMMDD )
{
if ( ! refind('^\d{8}$' , Arguments.YYYYMMDD ) )
throw "Invalid Format. Expected YYYYMMDD";
return parseDateTime
( Arguments.YYYYMMDD.replaceAll('(?<=^\d{4})|(?=\d{2}$)','-') );
}
function formatYMD( DateObj )
{
return DateFormat( DateObj , 'yyyymmdd' );
}
By using date objects it means that any level of developer can work with them, without needing to care about formatting, via built-in functions like DateAdd, DateCompare, and so on.
I'm not a regular expression fan since it's not that readable to me.
Since you're using CF9, I'd typed the argument and specify the returntype of the functions to be even more readable for the next person picking up your code.
First, right after I read the date from DB, I'd parse it to a Date object using parseDBDate()
Date function parseDBDate(required String dbDate)
{
var yyyy = left(dbDate, 4);
var mm = mid(dbDate, 4, 2);
var dd = right(dbDate, 2);
return createDate(yyyy , mm, dd);
}
Once you have the date object, you can use all those built-in Date functoin like DateAdd() or DateDiff().
Call browserDateFormat() right before you need to display it.
String function browserDateFormat(required Date date)
{
return dateFormat(date, "MM/DD/YYYY");
}
Call dBDateFormat() inside <cfqueryparam value=""> when it's time to persist to DB
String function dBDateFormat(required Date date)
{
return dateFormat(date, "YYYYMMDD");
}
One liner :)
myDateString = "20110203";
myCfDate = createObject("java","java.text.SimpleDateFormat").init("yyyyMMdd").parse(myDateString,createObject("java","java.text.ParsePosition").init(0*0));
If you want to parse different patterns, change "yyyyMMdd" to any other supported pattern.
http://download.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html
The ParsePosition is used to say where to start parsing the string.
0*0 is shorthand for JavaCast("int",0) - in the Adobe cf engine, 0 is a string, until you apply math to it, then it becomes a Double, which the ParsePosition constructor supports. Technically, it constructs with an int, but cf is smart enough to downgrade a Double to an int.
http://download.oracle.com/javase/1.5.0/docs/api/java/text/ParsePosition.html