Convert String to date (european to american) [duplicate] - php

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 6 years ago.
I have a String on the form: "dd/mm-yyyy", where dd is day of the month with two digits, mm is the month represented with two digits, and yyyy is the year with four digits.
I need to store this in my database. Ive tried
$dato = date('d/m-Y' ,strtotime($_POST['dag'] )
But that clearly doesnt work. In my database the date displays as yyyy-mm-dd. How do I properly convert the String to the correct format?

strtotime not accept your time string format, so it return false. You can use DateTime::createFromFormat or date_create_from_format, manual here.
DateTime::createFromFormat('d/m-Y', $_POST['dag']);
check the live demo
<?php
var_dump(DateTime::createFromFormat('d/m-Y', '11/01-2017'));
putput:
object(DateTime)#1 (3) {
["date"]=>
string(26) "2017-01-11 14:34:53.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(3) "UTC"
}

Try to replace the / with a - like so:
$date = "02/04-2016";
$dateNew = str_replace("/","-",$date);

You can use DateTime::createFromFormat:
$time = '12/3-1987';
$data = DateTime::createFromFormat('d/m-Y', $time);
echo $data->format('Y-m-d'); //1987-03-12
sandbox

Related

parse int to datetime with carbon

I have an example value of : 20160530105130
Which I want to convert to a datetime.
I have tried Carbon::createFromFormat('Ym',$value)
But that just errors.
I also tried with timestamp, but again error.
Anyone have an idea how I can achive this?
Create a DateTime or Carbon object from the string and use the year and month there.
$str = '20160530105130';
$dt = DateTime::createFromFormat('!Ym????????',$str);
var_dump($dt);
//object(DateTime)#2 (3) { ["date"]=> string(26) "2016-05-01 00:00:00.000000"
Demo: https://3v4l.org/bOJdU
With carbon:
$str = '20160530105130';
$dt = Carbon::createFromFormat('!Ym????????',$str);
echo $dt; //2016-05-01 00:00:00
Alternatively, the string can also be completely parsed with DateTime. The day and time can then be set to the desired values using the modify method. This variant makes it easier to read what is being done.
$str = '20160530105130';
$dt = date_create($str)->modify('first day of this month 00:00');
//object(DateTime)#2 (3) { ["date"]=> string(26) "2016-05-01 00:00:00.000000"
Carbon::createFromFormat('YmdHis', "$value")

Convert atom timestamp with timezone in php

I have some json data which contains timestamps in atom format.
Some examples of timestamps:
2020-04-12T04:05:08.92949232Z
2020-03-24T22:59:13.447142853+01:00
I'm trying to convert these with 'date("Y-m-d g:i:s",strtotime($atom)' but It seems to have problems with the +timezone format.
It works fine with $atom = "2020-04-12T04:05:08.92949232Z".
But if $atom = "2020-03-24T22:59:13.447142853+01:00" I get 1970-01-01 12:00:00.
I've played around with DateTime::createFromFormat but I just cant get it to work.
Is this possible to parse without to much effort or do I have to shoot the guy creating the json files?
DateTime causes problems if there are more than 6 digits after the period.
You must limit the digits to a maximum of 6 after the decimal point, then the expressions will be accepted.
$strDate = '2020-03-24T22:59:13.447142853+01:00';
//reduce microseconds to a maximum of 6
$strDate = preg_replace_callback('~\.\d{7,}~',function($match){
return ltrim(sprintf('%0.6F',$match[0]),'0');
},$strDate);
$d = date_create($strDate);
var_dump($d);
//object(DateTime)#2 (3) { ["date"]=> string(26) "2020-03-24 22:59:13.447143" ["timezone_type"]=> int(1) ["timezone"]=> string(6) "+01:00" }

Convert a String with GMT to DateTime Format - php [duplicate]

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 3 years ago.
I face this problem to integrate bKash Online Payment Gateway API.
The Documentation is here - https://developer.bka.sh/docs/create-payment-1.
In 'Create Payment' section bKash return paymentCreateTime string as following format.
2020-01-07T11:55:34:438 GMT+0600
How can I convert it to 2020-01-07 11:55:34 to save in MySQL?
I find a solution like following way.
$input = "2020-01-07T11:55:34:438 GMT+0600" // "2020-01-07T11:55:34:438 GMT+0600"
$timestamp = substr($input,0,19); // "2020-01-07T11:55:34"
$mysql = date_format(date_create($timestamp),'Y-m-d H:i:s'); // "2020-01-07 11:55:34"
But I need a solution without substr() function.
You can use createFromFormat() to directly parse your string.
Importantly, you'll need to escape T and GMT.
Everything else in https://www.php.net/manual/en/datetime.createfromformat.php
$input = '2020-01-07T11:55:34:438 GMT+0600';
$date = DateTime::createFromFormat('Y-m-d\Th:i:s:u \G\M\TO', $input);
echo $date->format('Y-m-d h:i:s');
This will cleanly deliver an object that you can format however you like.
Here is a demonstration:
$date = new DateTime("now");
echo $date->format('Y-m-d\Th:i:s:u \G\M\TO');
echo "\n---\n";
$input = '2020-01-07T11:55:34:438 GMT+0600';
echo $input;
echo "\n---\n";
$date = DateTime::createFromFormat('Y-m-d\Th:i:s:u \G\M\TO', $input);
echo $date->format('Y-m-d h:i:s');
echo "\n===\n";
var_dump($date);
Demonstration Output:
2020-01-07T10:12:53:000245 GMT+0100
---
2020-01-07T11:55:34:438 GMT+0600
---
2020-01-07 11:55:34
===
object(DateTime)#2 (3) {
["date"]=>
string(26) "2020-01-07 11:55:34.438000"
["timezone_type"]=>
int(1)
["timezone"]=>
string(6) "+06:00"
}
You can use it like this
date_default_timezone_set("Asia/Dhaka");
$mysql1 = date_format(date_create(strtotime($input)),'Y-m-d H:i:s');
it will print 2020-01-07 09:17:23

Convert PHP date format [duplicate]

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 3 years ago.
I have a simple section in which a user can select a range of date.
PHP to get these dates from datepicker
if (isset($_POST['from_date']) && isset($_POST['to_date'])) {
$firstDate= $_POST['from_date'];
$lastDate= $_POST['to_date'];
var_dump($firstDate);
var_dump($lastDate);
}
From the above PHP script, I am getting this
string(10) "08/13/2019"
string(10) "08/14/2019"
But I want this
string(10) "2019-08-13"
string(10) "2019-08-14"
What do I need to do to achieve what I want?
You can use strtotime() :
$time = strtotime('08/13/2019');
$newformat = date('Y-m-d',$time);
echo $newformat;
// 2019-08-13

DateTime not working for dates before 1970 [duplicate]

This question already has an answer here:
Create Date object in PHP for dates before 1970 in certain format
(1 answer)
Closed 4 years ago.
PHP v 5.6.2
I need to convert dates such as 18-Jul-46 to give me 18/07/1946 and no amount of DateTime functions work correctly. (As strtotime wont work for dates before 1970). They all end up giving 18/07/2046 which is incorrect.
Codes I tried so far:
$date = new DateTime("18-Jul-46");
$date->format('d/m/Y');
Another one with DateTime
$date = DateTime::createFromFormat('d-M-y', "18-Jul-46");
$date->format('d/m/Y');
Earlier also tried,
$date = date('d/m/Y', strtotime('18-Jul-46'));
None of them gave me the correct format. Any pointers or help is appreciated.
Thanks in advance!
If you have a date such as '31-Dec-18", it is ambiguous since it may refer to a date in 1918 or else a date in 2018. However, if you know that all the dates refer to the 1900s, then code such as the following is feasible given a two-digit year:
<?php
$now = new DateTime();
$formatted = "";
$arrFormattedBDays = [];
$birthdays = ['18-Jul-46','19-Aug-47','1-Jan-19','31-Dec-18'];
foreach ($birthdays as $b){
list($d,$m,$y) = explode("-",$b);
$y = '19'.$y;
$dt = new DateTime("$d-$m-$y");
$formatted = $dt->format('d/m/Y');
$arrFormattedBDays[] = $formatted;
}
var_dump($arrFormattedBDays);
Output:
array(4) {
[0]=>
string(10) "18/07/1946"
[1]=>
string(10) "19/08/1947"
[2]=>
string(10) "01/01/1919"
[3]=>
string(10) "31/12/1918"
See live code
Otherwise, by default DateTime creates a date object based on the current year which you may format according to the truth you seek to perpetuate; see here. Note: if you know that the dates all occur in the 20th century, i.e. 1901-2000, then you may amend this code by adding in a little logic; see here.
The computer doesn't know whether you mean 2000 or 1900. You can just take the last 2 digits of the year and put "19" before like:
$date = new DateTime("18-Jul-46");
$date->format('d/m/19y');
If you want to use 2000 as well, this code will use the closest number to 1970
$date = new DateTime("18-Jul-20");
$date->format('d/m/Y');
$t1 = $date->format('19y');
$t2 = $date->format('20y');
if(abs(1970-$t1)<abs(1970-$t2))
echo $t1; //Take the 19.. one
else
echo $t2; //Take the 20.. one
But in the end, you can't be sure that even 2030 would be correct.

Categories