11/08/2018, 20:43
strtotime note
Hàm strtotime của PHP có đặc điểm: Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y ...
Hàm strtotime của PHP có đặc điểm:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
Nghĩa là:
- Nếu bạn nếu bạn có một chuỗi theo thứ tự ngày, tháng, năm thì nên đặt dấu '-' ở giữa. VD: '25-03-2015'
- Ngược lại nếu bạn có tháng, ngày, năm thì nên đặt dấu '/' ở giữa. VD: '04/24/1992'
Có thể dùng hàm str_replace để thay đổi giữa 2 kí tự '-' và '/'
#Test datetime formating with dash
$timeWithDash = "25-03-1992";
$timeWithDashError = "03-25-1992";
#sucess formating
var_dump(strtotime($timeWithDash));
//output: int 701481600
#error formating return boolean false as result
var_dump(strtotime($timeWithDashError));
//output: boolean false
#Fix error with strtotime European format
$timeWithDashFix = str_replace('-', '/', $timeWithDashError);
var_dump($timeWithDashFix);
//output: string '03/25/1992' (length=10)
var_dump(strtotime($timeWithDashFix));
//output: int 701481600
#Test datetime formating with slash
$timeWithSlash = "04/19/1992";
$timeWithSlashError = "19/04/1992";
#sucess formating
var_dump(strtotime($timeWithSlash));
//output: int 703641600
#error formating return boolean false as result
var_dump(strtotime($timeWithSlashError));
//output: boolean false
#Fix error with strtotime American format
$timeWithSlashFix = str_replace('/', '-', $timeWithDashError);
var_dump($timeWithSlashFix);
//output: string '03-25-1992' (length=10)
var_dump(strtotime($timeWithSlashFix));
//output: int 703641600