-1

I have access to a set of date and times as so dd/mm/yy hh:mm so as an example 15/05/24 14:00, I am trying to set this to be an input for mySql DateTime format, however when I do it the system thinks the first number is the year not the last number.

Can I tell PHP that the initial date input was dd/mm/yy?

I have this setup to create the format for the DateTime but as I say its output is putting the first number as the year not the last.

$strtime[] = date("Y-m-d H:i:s", strtotime(str_replace('/', '-',$time)));

4
  • You can use DateTime, see: 3v4l.org/ZKqYi but several other solutions are possible. Commented May 22 at 17:47
  • @Nicolas Their format string is in the output function, not parsing. Commented May 22 at 17:48
  • 2
    See DateTime::createFromFormat(), which allows you to specify the format of the input. Commented May 22 at 17:49
  • 1
    Thank you very much KIKO Software, I didn't think of that method and It has worked perfectly thanks. Commented May 22 at 17:51

1 Answer 1

-2

Regexp solves everything!

<?php $time="15/05/24 14:00"; $sql_time=preg_replace('#^(\d+)/(\d+)/(\d+) (.*)$#','20$3-$2-$1 $4:00',$time); echo $sql_time; //2024-05-15 14:00:00 

https://3v4l.org/nkD4n

Sign up to request clarification or add additional context in comments.

6 Comments

DateTime::createFromFormat() is a better solution.
I appreciate that will create the answer, however the DateTime::createFromFormat() is the better method for me, plus it looks cleaner. Thanks though.
Spend some time to learn regular expressions, they are really helpfull in many cases.
If your only tool is a hammer then every problem looks like a nail. But you're right, regular expressions can be useful. In this case however there is a more standard method to solve this problem.
It is impossible to answer closed question. I answered before it. How could I know that it will be closed? Here are MILLIONS of people and you are again selecting me to downvote? Thanks a lot!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.