The Web Blinders logo

Programming

PHP Converting date from one format to another

<?php
/**
 * We are using CreateFromFormat
 * because date format differs in different time zones
 * for eg: YYYY-MM-DD in some and DD-MM-YYYY in others etc
 */
function convertDate($givenDate,$fromFormat,$toFormat){
    return DateTime::CreateFromFormat($fromFormat, $givenDate)->format($toFormat);
}
// 23 Nov 2019
var_dump(convertDate('2019-11-23','Y-m-d','j M Y'));
// 26 Aug 2019
var_dump(convertDate('26-08-2019','d-m-Y','j M Y'));

PHP Converting YYYY-MM-DD to DD-MM-YYYY

<?php
//  23-02-2019
var_dump(convertDate('2019-02-23','Y-m-d','d-m-Y')); 

PHP Converting DD-MM-YYYY to YYYY-MM-DD

<?php
//  2019-12-31
var_dump(convertDate('31-12-2019','d-m-Y','Y-m-d'));
 

Visit official documentation to know different characters recognized in the format().

Need developers ?

if so, send a message.

thewebblinders@gmail.com

More Programming from our blog

SEARCH FOR ARTICLES