How to convert date from one format to another? - php

I'm having the date in this format in a Excel worksheet 03-Dec-10. So its not compatible while inserting it into the database. How to convert the date to the acceptable format?

$input = '03-Dec-10';
$date = DateTime::createFromFormat('d-M-y', $input);
echo $date->format('Ymd'); // or possibly 'Y-m-d'
This will output 20101203, which is presumably what you want. If it's not exactly what you are after, have a look here.
You can also do the reverse:
$input = '20101203';
$date = DateTime::createFromFormat('Ymd', $input);
echo $date->format('d-M-y');

While Jon's answer is correct, here is another option:
$input = '03-Dec-10';
$date = date('Ymd', strtotime($input));

For a more general approach, you can always dump your current format to a string, like how you have it, and use string operations to substring and reorganize. I know for a fact that MySQL accepts string values for DATETIME fields.
$day = substr($input, 0, 2);
$month = substr($input, 2, 3);
switch($month){
case "Jan":
$month = "01";
break;
...
}

If you're doing this from Excel itself, you can put this formula into another column
=TEXT(A2, "YYYYmmdd")
Then copy down. This produces a compatible 8-digit date.

Related

Converting a non standard date string to a mysql datetime string using php

My intention is to convert the following date
20/04/17 13:27:5
to this
20-04-2017 13:27:05
I tried the typical date format functions of php and also Carbon...
things like
$newDate= Carbon::createFromFormat('d/m/y H:m:s', $originalDate);
in this case
var_dump($newDate->toDateTimeString()) would bring 2019-03-20 13:00:55 which is not what I expect.
So I was not lucky....is there a way to do this in a straight forward manner?
I think this should work.
$date = "20/04/17 13:27:5";
$sec = substr($date, strrpos($date, ":") + 1);
$sec = substr("0{$sec}", -2);
$new = substr($date, 0, strrpos($date, ":") + 1) . $sec;
$newDate = Carbon::createFromFormat('d/m/y H:i:s', $new);
I changed the format since you were using m twice for "minutes" and "month". It is correct for the month, but not for the minutes. Instead use i for minutes with leading zeroes.
$sec Is what I used to get the second from the string. This gets the last position of : and will take everything after it. This assumes that you do not change the format of the string.
substr("0{$sec}", -2) Adds a zero to the current second and extracts the last two characters. That means that 50 becomes 050 and then the last two characters are 50 so we end up without the padding, but 5 becomes 05 and the last two characters are the only characters.
$new concatenates the start of the date string and the new second with the zero padding.
$newDate is your original string with the format changed.
There is issue with seconds. There must be 05 not only 5
<?php
$original_date = "20/04/17 13:27:5";
$date_explode = explode(":", $original_date);
$date_explode[2] = str_pad($date_explode[2],2,"0",STR_PAD_LEFT);
$original_date = implode($date_explode,":");
$date = DateTime::createFromFormat('d/m/y H:i:s', $original_date);
echo date_format($date,"d-m-Y H:i:s");
?>
This is a working conversion routine that creates the ISO format you are looking for. But as already mentioned you need to "fix" the strange way the seconds are specified in the original example you provide. You will have to use string functions if that really is the format you receive. Better would be to fix the code that creates such broken formats.
<?php
$input = '20/04/17 13:27:05';
$date = DateTime::createFromFormat('d/m/y H:i:s', $input);
var_dump($date->format('d-m-Y H:i:s'));
The output obviously is:
string(19) "20-04-2017 13:27:05"
Isn't it like this?
$newDate = Carbon::createFromFormat('d/m/y H:i:s', $originalDate);

Convert MMDDYYYY to date for PHP [duplicate]

This question already has answers here:
Parse and reformat a datetime string
(6 answers)
Closed 11 months ago.
I have a string with a date which is in this format MMDDYYYY (ie. 01132012, 01142012 etc.)
I need to do something on a page, if that string is 14 days or less from the current date.
ie. Today is 01132012, so any strings with 12312011 or a less date are going to be showing something on a page.
Can anyone help with this? I've tried
echo date("d/m/Y", strtotime('01142012'));
But to no avail.
You can use the DateTime class of PHP
<?
// current date
$now = new DateTime();
//your date
$date = DateTime::createFromFormat('mdY', '01142012');
// calculate difference
$diff = $now->diff($date);
...
// output the date in format you want
echo $date->format('d/m/Y');
?>
EDIT: I just realized, that your format isn't one supported by php. So you have to use alternate objectbuild.
I prefer using strptime.
<?
$dt = strptime('01142012', '%m%d%Y');
echo sprintf("%02d/%02d/%04d", $dt['tm_mday'], $dt['tm_mon']+1, $dt['tm_year']+1900);
If you use PHP 5.3 or above, you can also use date_parse_from_format()
How about some substr + mktime?
$string = '01142012';
$time = mktime(0, 0, 0,
substr($string, 0, 2),
substr($string, 2, 2),
substr($string, 4, 4)
);
echo date('d/m/Y', $time);
try date('m-d-y', strtotime('01142012'));
could also try something like;
$var = strtotime('01142012');
$var2 = date ('F j, Y', $var);
Your string input of '01142012' cannot be parsed by strtotime() as it is not a valid as it is returning -1 as an answer. To convert this into a valid date you will need to add either slashes or dashes to separate the numbers.
The easiest way would be to store the dates with the dashes or slashes, such as '01-14-2012' or '01/14/2012' in the database from now on or you are going to have to create your own function to convert the numbers into a valid form for strtotime().
To do this you could do something like this:
function makeValidDate($date) {
$valid_date = array();
$array = str_split($date); //split characters up
foreach($array as $key => $character){
if($key==2 || $key==4){
$character = '-'.$character; //add relevant formatting to date
$valid_date[] = $character; //add this to the formatted array
}
else{
$valid_date[] = $character; // if not dashes or slashes needed add to valid array
}
}
return implode($valid_date); // return the formmatted date for use with strtotime
}
You can then do this to get a valid date:
$valid_date = makeValidDate('01142012');
echo date("d/m/Y", strtotime($valid_date));
I haven't tested this but you should get a good idea of what to do.
EDIT: Capi's idea is a lot cleaner!!
try "preg_match(pattern,string on wich the pattern will be aplied)";
http://www.php.net/manual/en/function.preg-match.php
you can also define an offset. so first take te first 2 digits. than take the other 2 digits and after that get the other four digits. after that place them in one string. after that use maketime,strtotime,date. this kind of stupid solution but i only thought of that. hope this will help

php date conversion between different formats

I've some data which formatted like: 04.09.1953
I want to convert this format to: 1953-09-04
Is there any way or php function to do this?
just use strtotime() to get a timestamp and then date() to convert that timestamp to the format you need:
$timestamp = strtotime("04.09.1953");
echo date("Y-m-d", $timestamp);
EDIT:
If you're having some "exotic" format as input, you might need to use explode(), list() and mktime() to build the timestamp on your own:
list($y,$m,$d) = explode(".","04.09.1953");
$timestamp = mktime(0,0,0,$m,$d,$y);
echo date("Y-m-d", $timestamp);
Have you tried strtotime() ? It might work, else you'll need to do manual conversion using substrings or explodes.
http://php.net/strtotime
http://php.net/substring
http://php.net/explode
If all you are interested in is converting from one "string" format to another you can use a regEx:
$DMY = '04.09.1953';
$YMD = preg_replace('/(\d\d).(\d\d).(\d{4,4})/', '$3-$2-$1', $DMY);
http://www.handyphp.com/index.php/PHP-Resources/Handy-PHP-Functions/reformat_date.html
function reformat_date($date, $format){
$output = date($format, strtotime($date));
return $output;
}

change dd/mm/yy date format to yy/mm/dd using php

I'm having date 20/12/2001 in this formate . i need to convert in following format 2001/12/20 using php .
$var = explode('/',$date);
$var = array_reverse($var);
$final = implode('/',$var);
Your safest bet
<?php
$input = '20/12/2001';
list($day, $month, $year) = explode('/',$input);
$output= "$year/$month/$day";
echo $output."\n";
Add validation as needed/desired. You input date isn't a known valid date format, so strToTime won't work.
Alternately, you could use mktime to create a date once you had the day, month, and year, and then use date to format it.
If you're getting the date string from somewhere else (as opposed to generating it yourself) and need to reformat it:
$date = '20/12/2001';
preg_replace('!(\d+)/(\d+)/(\d+)!', '$3/$2/$1', $date);
If you need the date for other purposes and are running PHP >= 5.3.0:
$when = DateTime::createFromFormat('d/m/Y', $date);
$when->format('Y/m/d');
// $when can be used for all sorts of things
You will need to manually parse it.
Split/explode text on "/".
Check you have three elements.
Do other basic checks that you have day in [0], month in [1] and year in [2] (that mostly means checking they're numbers and int he correct range)
Put them together again.
$today = date("Y/m/d");
I believe that should work... Someone correct me if I am wrong.
You can use sscanf in order to parse and reorder the parts of the date:
$theDate = '20/12/2001';
$newDate = join(sscanf($theDate, '%3$2s/%2$2s/%1$4s'), '/');
assert($newDate == '2001/12/20');
Or, if you are using PHP 5.3, you can use the DateTime object to do the converting:
$theDate = '20/12/2001';
$date = DateTime::createFromFormat('d/m/Y', $theDate);
$newDate = $date->format('Y/m/d');
assert($newDate == '2001/12/20');
$date = Date::CreateFromFormat('20/12/2001', 'd/m/Y');
$newdate = $date->format('Y/m/d');

php make date with format mm-dd-yyyy

I have a date in the following format
MM-DD-YYYY
How can I convert this to UNIX time in PHP
Thanks
Having a small problem
$date = strtotime($_POST['retDate']);
print $date; //Prints nothing
print $_POST['retDate']; //Prints 08-18-2009
If the format is always like that, I'd would try something like:
list($m,$d,$y) = explode('-', '08-18-2009');
$time = mktime(0, 0, 0, $m, $d, $y);
print date('m-d-Y', $time);
As for your example, the problem is the function fails. You should check it like so:
if(($time=strtotime('08-18-2009'))!==false)
{
// valid time format
}
else
echo 'You entered an invalid time format';
or you can use php date obyek to do that, like this
$tgl = "30-12-2013";
$tgl2 = DateTime::createFromFormat('d-m-Y', $tgl);
print_r($tgl2);
echo($tgl2->format('Y-m-d'));
i hope this can help...
Use strtotime:
$str = "03-31-2009";
$unixtime = strtotime($str);
Since these answers and comments were provided, PHP has updated to include a native function that suits this situation perfectly. Check out PHP's DateTime object here. This includes a createFromFormat method that will do as requested. In this particular example:
$date = DateTime::createFromFormat('j-M-Y', $_POST['retDate']);
From there, you can format it as desired or perform any other date operations:
echo $date->format('Y-m-d');
And that's it! Keep in mind that this is only provided in PHP 5.3.0 or higher!

Categories