Convert mm / dd / yy to mm / dd / yyyy in PHP

I am working on a project that requires me to read values ​​from a file and manipulate them a bit before storing them elsewhere. One of the things I need to do is convert some dates from mm / dd / yy format to mm / dd / yyyy format. Unfortunately for me, I am relatively new to PHP and regular expressions (which I believe is one of the best ways to solve this problem), and therefore I am somewhat puzzled. Any help would be greatly appreciated. Thank!

+3
source share
4 answers

PHP has a built-in functionstrtotime() designed only for this kind of task ... it will even make the best guess for the two-digit year following this rule: values ​​between 00-69 are mapped from 2000-2069 and 70-99 to 1970-1999. If you have a UNIXy-style date / time that PHP prefers, you can print it, but you want, date()function .

<?php
$str = '02/28/98';

// in PHP 5.1.0+, strtotime() returns false if it fails
// previous to PHP 5.1.0, you would compare with -1 instead of false
if (($timestamp = strtotime($str)) === false) {
    echo "Couldn't figure out the date ($str)!";
} else {
    echo "Reformatted date is " . date('m/d/Y', $timestamp);
}
?>

(I believe that here we are temporarily irrelevant, or this will add complexity).

+5
source

You can try this, it may or may not work:

$new_date = date( 'm/d/Y', strtotime( $old_date ) );

Where $old_dateis it in the format you are talking about.

+2
source

, YY, , , 19YY, 20YY. , . $cutOff YY $cutOff, 20YY, , 19YY

You can do this with a regular expression, but since your example is simple and the regular expression tends to be slower, you can just use string manipulation with substr and substr_replace .

Here's how to change the line mm / dd / yy int mm / dd / yyyy:

<?php
// Our date
$str = "01/04/10";
$cutoff = 50;
// See what YY is
// Get the substring of $str starting two from the end (-2)... this is YY
$year = substr($str, -2);
// Check whether year added should be 19 or 20
if ($year < 50)
    // PHP converts string to number nicely, so this is our 20YY
    $year += 2000;
else
    // This is 19YY
    $year += 1900;
// Repace YY with YYYY
// This will take $str and replace the part two from the end (-2) undtil 
// the end with $year.
$str = substr_replace($str, $year, -2);  
// See what we got
echo $str;
?>
+2
source

You can add a year starting with two values ​​(19 or 20), as shown below:

//for $s_date = "yy-dd-mm"
if (substr($s_date,6,2) >= 50){
    $standarddate  = "19" . substr($s_date,6,2); //19yy
    $standarddate .= "-"  . substr($s_date,0,2); //mm
    $standarddate .= "-"  . substr($s_date,3,2); //dd
} else {
    $standarddate  = "20" . substr($s_date,6,2); //20yy
    $standarddate .= "-"  . substr($s_date,0,2); //mm
    $standarddate .= "-"  . substr($s_date,3,2); //dd
}
// you will get yyyy-mm-dd
0
source

Source: https://habr.com/ru/post/1754719/


All Articles