How can I validate UTC date - php

I'd like to validate UTC date, sent by the POST request, before inserting it into my database.
$date = "2014-08-11T16:32:13.000Z"
What is the best way to check if the date is correct?

try {
$dt = new DateTime($date);
// $dt->format(DateTime::ATOM); // contains valid date
}catch(Exception $exception) {
// invalid $date
}

Related

PHP DateTime failing to convert Amazon shipping date

I've realised my DateTime function is not converting and returning false.
Example date/time as provided by Amazon. This is what I am trying to convert from:
2020-07-28T23:00:00Z
Function which accepts the date as provided by Amazon and tries to convert it.
protected function dateUtcToEuropeLondon($date)
{
try {
$dt = new DateTime($date, new DateTimeZone('UTC'));
$dt->setTimezone(new DateTimeZone('Europe/London'));
return $dt;
} catch (Exception $e) {
return false;
}
}
Full function.
// Detect if custom shipping date exists
$date = (isset($order_details->EarliestShipDate)) ? $order_details->EarliestShipDate : '';
// Set custom meta field so we can easily access it via WC_Order
if (!empty($date)) {
$date = $this->dateUtcToEuropeLondon(strtotime($date));
if ($date instanceof DateTime) {
update_post_meta($order_id, '_wpl_shipping_date', $date->format('Y-m-d\TH:i:s'));
}
}
For starters, I checked what value I got back from:
$date = $this->dateUtcToEuropeLondon(strtotime('2020-07-28T23:00:00Z'));
it was nothing: ''.
The problem is that you're trying to create a DateTime object using a UNIX timestamp (via strtotime) which is all numbers. What DateTime is expecting is the more 'human friendly' d/m/y style format - so you'll need to specify that what you're giving it is a 'unixtime' string, rather than a 'datetime' string -- subtle difference.
Try changing
$dt = new DateTime($date, new DateTimeZone('UTC'));
to
$dt = new DateTime('#'.$date, new DateTimeZone('UTC'));
Using an # at the start of the string will tell your DateTime object that you're sending in a unix timestamp. Once it's happy, it will then allow your function to determine the correct timezone from UTC to Europe/London (GMT/BST).

Setting PHP date time format

I have a column in a MySQL table that is of type 'datetime'.
How do I get a value from php of the current date and time with the format - for example: "2014-11-09 15:06:51" and set into a variable?
thanks.
check this PHP documentation for more clarification.
$DateTime = date('Y-m-d H:i:s');
Ref
You can use CURDATE() of MySql. No need of using php for this.
INSERT INTO `db`.`data1` (
`id` ,
`date`
)
VALUES (
'2', CURDATE()
)
See for more documentation http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_curdate
Well if you're doing this in a class you could use my DateTime getter and setter. Assumes that $this->Date is a php DateTime object and you're using mysql with a DATETIME column.
Here's what using it looks like:
$this->setDate($whatever_date); // give it a timestamp, mysql DATETIME, or anything that can be read by strtotime()
// Need to put the date into mysql? Use this:
$this->getDate('mysql');
// Need to get the date so a person can read it?
$this->getDate('human');
// want it as a timestamp?
$this->getDate('unix');
Here's the methods:
// accepts 'human', 'mysql', 'unix', or custom date() string
function getDate($format='human'){
if(get_class($this->Date)!='DateTime') return FALSE;
try{
switch ($format) {
case 'human':
return $this->Date->format('M j, Y g:i a'); // Show date and time
// return $this->Date->format('M j, Y'); // Just the date
break;
case 'mysql':
return $this->Date->format('Y-m-d H:i:s');
break;
case 'unix':
return $this->Date->format('U'); // may return a negative number for old dates
break;
default:
return $this->Date->format($format);
break;
}
} catch (Exception $e){
throw new Exception('Can not use that format for getting DateTime');
return FALSE;
}
}
// Sets as a DateTime object - accepts either a timestamp or a date() string
function setDate($date){
try{
if(is_numeric($date) && (int)$date==$date){ // timestamp
$this->Date = new DateTime(date('F j, Y, g:i a', $date));
} else {
$this->Date = new DateTime($date);
}
} catch (Exception $e){
throw new Exception('Can not set the given value ('.$date.') as DateTime');
return FALSE;
}
return TRUE;
}
If you're not using classes you would want to combine them into a single function that takes the format you have and returns the format you need.

How to stop an invalid date from being sent to a database

I require a date to be entered in the correct format, and if it isn't then an error is shown. My PHP program looks like this:
if (empty($_POST["date"])) {
$dateErr = "Date is required";
} else {
$date = test_input($_POST["date"]); etc
This is just the standard way of showing error for an improper date format. But my problem is that even though an error is shown, there is nothing that is stopping that date (in the wrong format) from being passed into the database. When I check my database, I see that date and it is not what I want. Is there a way that a date written in the wrong format can be blocked from ending up on my database? Like a filter, I mean.
Use the powerful DateTime class, DateTime::createFromFormat is useful here, it returns a new DateTime instance or FALSE on failure.
So it will go this way:
if (empty($_POST["date"])) {
$dateErr = "Date is required";
} else {
$format = 'Y-m-d'; // write your format here
$date = DateTime::createFromFormat($format, $_POST["date"]);
if($date)
{
// add to database
}
Also your database field should be set as datetime which has the format Y-m-d, so before you insert it you have to format it to Y-m-d using PHP, like:
$date->format('Y-m-d');
That will return a proper string to insert in your database.
You should use a function to check whether the date given is in the appropriate format before you begin your db transaction. You can do this in the following approach using regular expressions as #Subhanker mentioned to match to the following format YYYY-MM-DD:
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $_POST['date']))
{
//Start DB transaction here
// Create connection
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$form_date = mysqli_real_escape_string($con, $_POST['date']);
$sql="INSERT INTO dates_table (dates)
VALUES ('$form_date')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}else{
$dateErr = "Date is required";
}
Please let me know if you have any questions!
You can use strtotime to do your checking. No regex needed
$date = strtotime($_POST["date"]);
if($date === false) $dateErr = "Unrecognized Date format";
else $date = date('m/d/Y', $date); // Set your own date format here
if (preg_match("/^(19|20)\d\d[\-\/.](0*[1-9]|1[012])[\-\/.](0*[1-9]|[12][0-9]|3[01])$/", $date )){//This will match the input in format YYYY-MM-DD
//Date ok
}else{
//Invalid Date
}

PHP/SQL - DateTime class - how to add automaticlly time if it's not inserted by the user

Now I sq use the DateTime class to convert to different time formats and I find it very useful except one feature. Before when the user try to add date but for some reason skip the time I got 00:00:00 for the time which was good enough for me. Now, with the DateTime class if the time is not included it return error.
Here is my code:
$dt = DateTime::createFromFormat("d.m.Y H:i:s", $data['event_time']);
if($dt === false)
{
throw new Exception("Invalid date");
}
$formattedDate = $dt->format('Y-m-d H:i:s');
Every time I try to insert date without time I get Invalid date error. Is there a way to insert zeros on the place of the time, except getting error for this?
Thanks
Leron
Some simple pre-validation:
$date['event_time'] = trim($date['event_time']);
if (preg_match('/^\d{2}\.\d{2}\.\d{4}$/', $date['event_time'])) {
$date['event_time'] .= ' 00:00:00';
} else if (!preg_match('/^\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}:\d{2}$/', $date['event_time'])) {
die('Invalid format');
}
If you don't want to use regex I guess this should work too. If i was you I would use #deceze solution instead of this :P but for the sake of completeness, here it is:
$dt = DateTime::createFromFormat("d.m.Y H:i:s", $data['event_time']);
if($dt === false)
{
$data['event_time'] = trim($data['event_time']);
$data['event_time'] .= " 00:00:00";
$dt = DateTime::createFromFormat("d.m.Y H:i:s", $data['event_time')
if ($dt === false) {
throw new Exception("Invalid date");
}
}
$formattedDate = $dt->format('Y-m-d H:i:s');

how to write a single function for getting different time zones in php?

I am creating a script that allows the user to choose their own timezone...
and enter the date $ time..So the user entered date/time must be converted to GMT format while storing into the database.
While retrieving from the database it should be again converted into original format.
Here DST concept must also be included.
So here date can be in a variable which can be a string or array(multidimensional array also)
So i tried like this.....
function ConvertOneTimezoneToAnotherTimezone($time,$currentTimezone,$timezoneRequired)
{
$current_zone = new DateTimeZone($currentTimezone);
//$gmt = new DateTimeZone('GMT');
$date = new DateTime($time, $current_zone);
//$date->setTimezone($gmt);
$date->setTimezone(new DateTimeZone($timezoneRequired));
return $date->format('Y-m-d H:i:s');
// Convert it back to Original timezone
$date->setTimezone($current_zone);
return $date->format('Y-m-d H:i:s');
}
$time='2011-03-29 11:15:00.000';
echo "Current Date/Time is=".ConvertOneTimezoneToAnotherTimezone($time,'Asia/Kolkata','America/New_York');
but here i am only able to convert into different timezones,but i want a single function which converts date/time and also while retrieving gives original format......
please anybody help me......
<?php
function ConvertOneTimezoneToAnotherTimezone($originalDateTime, $originalTimeZone, $targetTimeZone) {
$format = 'Y-m-d H:i:s';
$dateTime = new DateTime($originalDateTime, new DateTimeZone($originalTimeZone));
$original = $dateTime->format($format);
$dateTime->setTimezone(new DateTimeZone($targetTimeZone));
$target = $dateTime->format($format);
return compact('original', 'target');
}
$dateTime = '2011-03-29 11:15:00.000';
$converted = ConvertOneTimezoneToAnotherTimezone($dateTime,'Asia/Kolkata','America/New_York');
echo sprintf('Original Date/Time is=%s', $converted['original']), PHP_EOL;
echo sprintf('Converted Date/Time is=%s', $converted['target']), PHP_EOL;
something like this
http://service-kl.com/code/tz_demo2/?cou=USA

Categories