about date_format in php - php

I'm using PHP Version 5.5.15 and running php (on my local windows machine) with Xampp.
I have troubles with the variable $time. $date and $date2 are working.
here's the code:
<?php
//include_once('connect.php')
function currencyquote() {
$from = 'EUR';
$to = 'USD';
$url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='.$from .$to .'=X';
$handle = #fopen($url,'r');
if($handle) {
$result = fgets($handle, 4096);
fclose($handle);
}
$allData = explode(',',$result);
$date = $allData[2]; //ex.: "2/18/2015"
$time = $allData[3]; //ex.: "1:48pm" -> New York local time
$close = $allData[1]; // ex.: 1.3151
echo 'the $result = ' . $result .'<br />';
echo 'the $time = ' .$time. '<br />';
$date2 = date_create_from_format("h:ia","01:50pm");
echo 'the $date2 = ' . date_format($date2, "H:i:s") . "<br />";
$date3 = "01:50pm";
$date=date_create_from_format("h:ia",$date3);
echo 'the $date = ' . date_format($date,"H:i:s") . "<br />";
// this is what i want to use :
$time1 = date_create_from_format("h:ia", $time);
echo 'the $time1 = ' . date_format($time1,"H:i:s") . "<br /><br />"; // this line is line 30 of the code
//with strtotime:
echo 'using \'date\' = ' . date("h:i:s", strtotime($allData[3])) . "<br />";
echo 'using \'date()\': '.date('H:i:s', strtotime($time));
}
currencyquote();
?>
and here are the results of the php-jury:
the $result = "EURUSD=X",1.1372,"2/19/2015","7:20am"
the $time = "7:20am"
the $date2 = 13:50:00
the $date = 13:50:00
Warning: date_format() expects parameter 1 to be DateTimeInterface, boolean given in C:\xampp\htdocs\Nofrafin\php\downloader.php on line 30
the $time1 =
using 'date' = 01:00:00
using 'date()': 01:00:00

The message you get most likely means that $time1 is set to false. And the reason from that should be that date_create_from_format() can't match the date format h:is with the variable you supply, $time.
Moving further up, you have
$time = $allData[3]; //ex.: "1:48pm"
I tried changing to $time = '1:48pm'; and that worked perfectly. So that means you don't get the data you think from the csv.
I tried to download the same file as you do and got this back:
"EURUSD=X",1.1371,"2/19/2015","7:50am"
And that's the reason it doesn't work - $time is set to "7:50am" with a trailing newline, not 7:50am. Remove the double quotes (e.g. $time = trim(str_replace('"', '', $time)); and you should hopefully be fine. :)

Firstly:
For CSV reading use fgetcsv() function, so you will not have to filter quotes from CSV output and there is no need to do explode().
if($handle) {
$result = fgetcsv($handle, 4096);
fclose($handle);
}
$date = $result[2]; //ex.: "2/18/2015"
$time = $result[3]; //ex.: "1:48pm" -> New York local time
$close = $result[1]; // ex.: 1.3151
...
$time1 = date_create_from_format("G:ia", $time);
Secondly:
You should carefully filter the input string for date_create_from_format function.
such as:
$time = trim(str_replace("\"","", $time)); // you will get something like 7:20am
and then:
$time1 = date_create_from_format("G:ia", $time); // G - for 24-hour format without leading zeroes in your case
but use the first solution (fgetcsv()) anyway

Related

How to know if a date/time string contain day or not in php?

I want to check if a date/time string contains a day or not.
I used the date_parse() function but it automatically adds day => 1 if it doesn't find any day.
So I couldn't know if a string contains a day or not.
For example
$date = "2021-02";
How to know if this string contains a day or not?
The DateTime::createFromFormat method tests well that the format is adhered to. Entries like "2019-02-" or "2019-xx-23" are also recognized as incorrect.
$date = "2021-02-x";
$dateTime = DateTime::createFromFormat('Y-m-d',$date);
if($dateTime){
echo $date.' ok';
}
else {
echo 'wrong date '.$date;
}
I think you are expecting some thing like this.
<?php
$date1 = "2021-02";
$date2 = "2021-02-11";
$date3 = "2021-12";
$date4 = "2021-12-14";
$date1_array = explode("-", $date1);
$date2_array = explode("-", $date2);
$date3_array = explode("-", $date3);
$date4_array = explode("-", $date4);
if (count ($date1_array) == 3)
{
echo $date1 . ": It's a Date.";
echo "<br />";
}
if (count ($date2_array) == 3)
{
echo $date2 . ": It's a Date.";
echo "<br />";
}
if (count ($date3_array) == 3)
{
echo $date3 . ": It's a Date.";
echo "<br />";
}
if (count ($date4_array) == 3)
{
echo $date4 . ": It's a Date.";
echo "<br />";
}
?>

Convert timestamp with dots in PHP ("yyyy.mm.dd hh:nn:ss.zzz")

I'm trying to convert strings with hungarian datetime format, but no success because of the dot-separators:
<?php
$dtime = DateTime::createFromFormat("YY'.'MM'.'DD HH:MM:II frac", "2020.07.22 22:41:36.258");
$timestamp = $dtime->getTimestamp();
echo("Result: " . $timestamp . "<br>");
?>
Isn't it possible without "string-replace" like this:
strtotime(preg_replace("/([0-9]{4})\.([0-9]{2})\.([0-9]{2})/",'${1}-${2}-${3}',$xml->delivery_time)) ?
(I'm new to PHP 5 and I'm shocked it can not simply convert a common date format. Searched 200+ results, wasted 4+ hours ... no success.)
The correct format is stored in the $format variable:
(Note: the v (millisec) modifier has only been added since v7.3)
<?php
$format = 'Y.m.d H:i:s.v';
$dtime = DateTime::createFromFormat($format, "2020.07.22 22:41:36.258");
$timestamp = $dtime->getTimestamp();
echo("Result: " . $timestamp . "<br>");
?>
Result: 1595457696
This solution will also work for PHP versions below 7.3
// convert a hungarian datetime to a timestamp
function toTimestamp($dt)
{
$format = 'Y.m.d H:i:s.';
if (version_compare(PHP_VERSION, '7.3.0', '<')) {
$dt = explode('.', $dt);
$dt[3] = intval($dt[3] * 1000);
$dt = implode('.', $dt);
$format .= 'u';
} else {
$format .= 'v';
}
return DateTime::createFromFormat($format, $dt)->getTimestamp();
}
$timestamp = toTimestamp('2020.07.22 22:41:36.258');
var_dump($timestamp);

Set up cookie for page visit

I want to set up 2 cookies. One that shows how many times a user entered the page, and the other shows the date and the time of last visit.
The code works fine, but I need my cookies set up once a day, not every time I visit the page. What I need is to set the if($_COOKIE['lastTime'] != date('d-M-Y')) statement, but I need to compare only the 'd-M-Y' part of $_COOKIE['lastTime']. Also, I can't set $lastTime = date('d-M-Y') (without h-i-m-s), because I need to show the date AND the time of last visit.
Please, help.
$counter = 0;
if(isset($_COOKIE['counter'])){
$counter = $_COOKIE['counter'];
}
$counter++;
$lastTime = '';
if(isset($_COOKIE['lastTime'])){
$lastTime = $_COOKIE['lastTime'];
}
$lastTime = date('d-M-Y H-i-m-s');
if($_COOKIE['lastTime'] != date('d-M-Y')){
setcookie('counter', $counter);
setcookie('lastTime', $lastTime);
}
print_r('This is your ' . $_COOKIE['counter'] . ' visit');
echo '<br>';
print_r('Last visit was: ' . $_COOKIE['lastTime']);
I left commented lines in the scope, so you can see what can be optimised to get brevity to your code. Those commented lines are not needed at all.
print_r('Previous visit was: ' . isset($_COOKIE['lastTime'] ? date("Y-m-d", $_COOKIE['lastTime']) : 'not set yet'));
$counter = 0;
if(isset($_COOKIE['counter'])){
$counter = $_COOKIE['counter'];
}
$counter++;
$lastDay = '';
if(isset($_COOKIE['lastTime']) {
$lastDay = date("Y-m-d", $_COOKIE['lastTime']);
}
$currentDay = date("Y-m-d");
if(!$lastDay || $lastDay < $currentDay) {
setcookie('counter', $counter);
setcookie('lastTime', strtotime($currentDay));
}
print_r('This is your ' . $_COOKIE['counter'] . ' visit');
echo '<br>';
// here you print a readable datetime format from your stored date
print_r('Last stored visit date was: ' . date("Y-m-d", $_COOKIE['lastTime']));
use this:
$lastTime = date('d-M-Y');
and not this:
$lastTime = date('d-M-Y H-i-m-s');
Your code:
$lastTime = '';
if(isset($_COOKIE['lastTime'])){
$lastTime = $_COOKIE['lastTime'];
}
$lastTime = date('d-M-Y H-i-m-s'); <-- you're overwriting any retrieved value here
Check if you got a value first so you don't overwrite it, and then extract just the date part:
$lastTime = '';
if(isset($_COOKIE['lastTime'])){
$lastTime = $_COOKIE['lastTime'];
}
if(strlen($lastTime) == 0)
$lastTime = date('d-M-Y H-i-m-s');
$parts = explode(" ", $lastTime);
$lastDay = $parts[0];
if($lastDay != date('d-M-Y')){...

PHP Day count function writing

I need to Write a function named countDays which takes a single parameter named dateinstring which is string in the form ”MM.DD.YYY” represent a real date value. The function should print to the console the number of days from the beginning of the year specified in dateInString until the date represented in dateInString. If the value of dateInString is invalid, the function should print ”Bad format” to the console.
I have written the code as below :
function countDays($dateInString){
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if(count($date) == 3 && checkdate($date[0], $date[1], $date[2])){
$formatted_date = $date[2].'-'.$date[0].'-'.$date[1].'00:00:00';
$diff = strtotime($formatted_date).'-'.strtotime($date[2].'-01-01 00:00:00');
echo round($diff/86400)+1;
}
else {
echo 'Bad format';
}
};
countDays('1.15.2014');
But the above code seems that not giving the correct output. It is about 33% correct. But where is the problem with this code ? Please help me!!!
$diff = strtotime($formatted_date).'-'.strtotime($date[2].'-01-01 00:00:00');
Change to
$diff = strtotime($formatted_date) - strtotime($date[2].'-01-01 00:00:00');
You made the minus symbol a string instead of an operator.
You could try it this way
function countDays($dateInString) {
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if (checkdate($date[0], $date[1], $date[2])) {
$year_start = mktime(0, 0, 0, 1, 1, $date[2]);
$your_date = mktime(0,0,0,$date[0], $date[1], $date[2]);
$diff = $your_date - $year_start;
echo floor($diff /(60*60*24));
} else {
echo "Bad date supplied";
}
}
A better approach would be to use the DateTime class. I haven't included the validation in this, but i suggest you use regex for that.
function countDays($dateInString){
$parts = explode('.', $dateInString);
$date = new DateTime($parts[2] . '-' . $parts[0] . '-' . $parts[1]);
$compare = new DateTime( $date->format('Y') . '-01-01' );
$interval = $date->diff($compare);
return $interval->format('%a');
}
echo countDays('09.15.2014');
Check this out.
function countDays($dateInString){
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if(count($date) == 3 && checkdate($date[0], $date[1], $date[2])){
$formatted_date = strtotime($date[2].'/'.$date[0].'/'.$date[1]);
$endTimeStamp = strtotime("2014/01/01");
$timeDiff = abs($endTimeStamp - $formatted_date);
echo round(intval($timeDiff/86400));
}
else {
echo 'Bad format';
}
};
countDays('01.01.2014');

In PHP given an extended date string, how can I extract the month Year in long format?

My attempted solution was:
$date = "Nov 30 2009 03:00:00:000PM";
echo date("F Y", strtotime($date));
Expected result should be: "November 2009"
Any other simple solutions?
While a regex could do it, here's something you might understand easier
$date_bad = "Nov 30 2009 03:00:00:000PM";
$piece_date = array();
$piece_date = explode(' ', $date_bad);
$date_good = $piece_date[0] .' '. $piece_date[1] .', '. $piece_date[2] .' ';
$piece_time = array();
$piece_time = explode(':', $piece_date[3]);
// check if the last part contains PM
if ( is_numeric(strpos($piece_time[3], 'PM')) )
{
$ampm = 'PM';
}
// check if the last part contains AM
elseif ( is_numeric(strpos($piece_time[3], 'AM')) )
{
$ampm = 'AM';
}
// no AM or PM is there, so it's a 24hr string
else
{
$ampm = '';
}
$date_good .= $piece_time[0] .':'. $piece_time[1] .':'. $piece_time[2] . $ampm;
echo date("F", strtotime($date_good));
date_default_timezone_set ('Etc/GMT-6');
$unixtime = strtotime($date_bad);
$date = date("F Y",$unixtime);
echo $date;
Time Zones

Categories