If I have a PHP string in the format of mm-dd-YYYY
(for example, 10-16-2003), how do I properly convert that to a Date
and then a DateTime
in the format of YYYY-mm-dd
? The only reason I ask for both Date
and DateTime
is because I need one in one spot, and the other in a different spot.
Answers
Try using something like this:
if(strtotime('2011-08-19 17:14:40') < strtotime('-30 days')) {
// this is true
}
Besides, this string looks like it is stored in SQL as datetime/timestamp field. You can directly select all entries from your database with old dates using:
SELECT ... WHERE `datetime` + INTERVAL 30 DAY < NOW()
See strtotime() and date()
e.g., 2010-02-03 22:21:26
to 3rd February 2010 at 22:21
:
$DateTimeStr = '2010-02-03 22:21:26';
echo date('jS F Y at G:i', strtotime($DateTimeStr));
You are using the format pattern string yyyyMMdd
. You are parsing the date-time string 2018-06-20 00:00:00
.
2018
matches yyyy
. MM
means that month should be two chars, so -0
is taken for the month. And -0
or just 0 is taken to be the month before month 1 of 2018, that is, December 2017. Finally 6
is taken as the day of month. It should have been two chars too, but since there is only one digit, SimpleDateFormat
settles with that. The remainder of the string is tacitly ignored.
Exactly the same thing happens when parsing the other string.
It’s the long outdated SimpleDateFormat
class in a nutshell: In its attempts to be friendly and helpful it produces the most unpleasant and confusing surprises. Where you would have wished it would tell you something is wrong, it just pretends that everything is fine. It’s one of the main reasons that this class is considered troublesome, and why the replacement for the old classes came out with Java 8 more than 4 years ago. So just never use SimpleDateFormat
again.
Instead look into java.time
and its DateTimeFormatter
.
Also don’t get date values as strings from your database. Depending on the datatype that the query returns get either a LocalDateTime
or a LocalDate
object. This will free you completely from parsing.
Link: Oracle tutorial: Date Time explaining how to use java.time
.
One approach would be to use SimpleDateFormat to parse the strings to Date
objects and then do the comparisons through the Date
API.
Edit for change to Question:
Below is what I have tried.
SimpleDateFormat dateFormat = new SimpleDateFormat("mm/dd/yy"); TaskDate = dateFormat.parse(LinkStorage[i][1]); if (todayDate.after(TaskDate)) { System.out.println("") }
Unfortunately not getting desired output
The problem is with your format string, you are asking for Minutes and not Months. Change "mm/dd/yy"
to "MM/dd/yy"
and you should have better luck.
Use
strtotime()
on your first date thendate('Y-m-d')
to convert it back:Make note that there is a difference between using forward slash
/
and hyphen-
in thestrtotime()
function. To quote from php.net: