Comparing two dates in php

This feels lượt thích a stupid question and yên sure ive sầu used it before - I just want khổng lồ know if i compare dates like this ‘yyyy-mm-dd’ > ‘yyyy-mm-dd’ will it always return the right result. Sorry i know this may sound stupid.

Bạn đang xem: Comparing two dates in php

Ive done some testing and it always seems khổng lồ return the right result but when i searched google for comparing dates no one seem to lớn bởi it that way và it was all strtotime so i assumed that there must be something wrong with doing it the ‘Y-m-d’ way. If someone could just let me know if i can vày it this way then i would be grateful.


StarLion September 11, năm trước, 12:29pm #2

It SHOULD work correctly - comparison tests on strings (Which these are. PHPhường doesnt know the difference between a string & a date.) are done character-to-character, left khổng lồ right. 2 = 2, 0 = 0, 1>0, therefore string 1 > string 2.

IF your strings are guaranteed khổng lồ be in the format YYYY-MM-DD, there wont be a problem.If it was YYYY-DD-MM or DD/MM/YYYY or MM/DD/YYYY, you’d have problems.

Xem thêm: Bài Thuốc Dân Gian Chữa Ngứa Vùng Kín, 10 Cách Chữa Trị Viêm Âm Đạo Bằng Dân Gian

footballud September 3, 2014, 11:02am #3


Thanks for the quichồng response. I will do it as you have described but could you or someone tell me why i shouldn’t bởi it as:

if($date1 > $date2)//vày this else //bởi that

On all my testing it has worked okay - Just wanted lớn know when doing this could go wrong. I know the format of the timestamps is always going lớn be the same và i just wondered if i did it this at what point would i run into problems. By this i mean does comparing these under certain conditions return the wrong result.

Thanks again though for quiông chồng response

Raju_Gautam September 3, 2014, 11:02am #4

To kiểm tra if the given date is valid/correct format or not you can use checkdate(). But to lớn compare two dates it is better to convert those date khổng lồ seconds và compare.

Xem thêm: Phần Mềm Mmlive - Giới Thiệu App Mlive China Mới Hot

footballud September 3, năm trước, 11:04am #5
Thanks for that - exactly what i was looking for - I will use the strtotime to do them as can see why that would be best practice but wanted to understand why that would be best practice - The dates are created from a size & the formatted the same way everytime. Thanks for the pointer on before BCE as well as im not using those dates but is good lớn know for the future

Thanks for all the help - I love these forums.


StarLion September 11, 2014, 12:29pm #6

Slight addition: I’m assuming you’re not going khổng lồ be using dates that cross the 0 line. If you’re going khổng lồ use BCE dates, you need a different comparison.

Home Categories FAQ/Guidelines Terms of Service Privacy Policy

Powered by Discourse, best viewed with JavaScript enabled

Chuyên mục: