php make date with format mm-dd-yyyy - php

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!

Related

Date function in PHP Not working properly

While converting date format from mm-dd-yy hh:ii:ss to yy-mm-dd hh:ii:ss format using below code.
<?php
echo $start_date = date("Y-m-d H:i:s",strtotime("10-14-2015 00:00:00"));
?>
But the result is
1970-01-01 05:30:00
If it is not a proper way to use date ,provide me alternate way
First check this answer whats the difference between dates over here and simply use str_replace like as
echo $start_date = date("Y-m-d H:i:s",strtotime(str_replace("-","/","10-14-2015 00:00:00")));
Or you can also use DateTime::createFromFormat over like as
$date = DateTime::createFromFormat("m-d-Y H:i:s","10-14-2015 00:00:00");
echo $date->format('Y-m-d');
Demo
Read the manual: http://php.net/manual/en/function.strtotime.php
and also specify your PHP version.
It has a nice example on checking if strtotime conversion was successfull:
if (($timestamp = strtotime($str)) === false) {
And this conversion is very critical, it supports only limited number of formats that should be specified very precisely in order days/months/years, and separators / or - or :
So you have to pick the format that you will support from following list:
http://php.net/manual/en/class.datetime.php
Be sure to create culturally aware code (e.g. US/UK/... format)
Please write your code as below:
echo $start_date = date("Y-m-d H:i:s",strtotime("10/14/2015 00:00:00"));

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;
}

strtotime() converts a non existing date to another date

I am building a timestamp from the date, month and year values entered by users.
Suppose that the user inputs some wrong values and the date is "31-02-2012" which does not exist, then I have to get a false return. But here its converting it to another date nearby. Precisely to: "02-03-2012"..
I dont want this to happen..
$str = "31-02-2012";
echo date("d-m-Y",strtotime($str)); // Outputs 02-03-2012
Can anyone help? I dont want a timestamp to be returned if the date is not original.
You might look into checkdate.
That's because strtotime() has troubles with - since they are used to denote phrase like -1 week, etc...
Try
$str = '31-02-2012';
echo date('d-m-Y', strtotime(str_replace('-', '/', $str)));
However 31-02-2012 is not a valid English format, it should be 02-31-2012.
If you have PHP >= 5.3, you can use createFromFormat:
$str = '31-02-2012';
$d = DateTime::createFromFormat('d-m-Y', $str);
echo $d->format('d-m-Y');
You'll have to check if the date is possible before using strtotime. Strtotime will convert it to unix date meaning it will use seconds since... This means it will always be a date.
You can workaround this behavior
<?php
$str = "31-02-2012";
$unix = strtotime($str);
echo date('d-m-Y', $unix);
if (date('d-m-Y', $unix) != $str){
echo "wrong";
}
else{
echo date("d-m-Y", $unx);
}
or just use checkdate()
Use the checkdate function.
$str = "31-02-2012";
$years = explode("-", $str);
$valid_date = checkdate($years[1], $years[0], $years[2]);
Checkdate Function - PHP Manual & Explode Function - PHP Manual
Combine date_parse and checkdate to check if it's a valid time.
<?php
date_default_timezone_set('America/Chicago');
function is_valid_date($str) {
$date = date_parse($str);
return checkdate($date['month'], $date['day'], $date['year']);
}
print is_valid_date('31-02-2012') ? 'Yes' : 'No';
print "\n";
print is_valid_date('28-02-2012') ? 'Yes' : 'No';
print "\n";
Even though that date format is acceptable according to PHP date formats, it may still cause issues for date parsers because it's easy to confuse the month and day. For example, 02-03-2012, it's hard to tell if 02 is the month or the day. It's better to use the other more specific date parser examples here to first parse the date then check it with checkdate.

How to convert date from one format to another?

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.

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');

Categories