2

I have the following string which is pulled from an entry in a log file.

$d = "19/09/2014 22:41:27"

However, I need to convert it so that it is

2014-09-19 22:41:27

so that I can export it with other sections of the logfile into a MySQL database.

But I can't for the life of me find a way to do this. I was expecting to find something like set-dateFormat, which would simply re-map the components of the string, but it doesn't seem to exist.

I have tried various variations of the following:

$a = "19/09/2014 22:41:27"
$d = [datetime]::ParseExact($a, "dd/MM/yyyy hh:mm:ss", $null)
$e = "{0:yyyymmddhhmmss}" -f [datetime]$d

But everything returns the error:

String was not recognized as a valid DateTime.

What is the best way to get the format I need please?

1
  • The error about "String is not recognized as a valid DateTime" is due to your ParseExact date format. You have 24 hour time listed in string $a, but you are attempting to read it as 12hour time by using lower case "hh:". If you use "HH:" instead it converts fine. Commented Jan 29, 2015 at 3:22

2 Answers 2

6

A quick play around, with the help of a few other blogs provided the following, very similar to your own. There's probably a way to make it a little more streamlined, but it will create the datetime object you need. Manipulating the output after that should be straightforward.

$theDTString = "19/09/2014 22:41:27".toString()
$theDateTimeObject = ([datetime]::ParseExact($theDTString,"dd/MM/yyyy HH:mm:ss",$null))

$theDateTimeObject.year.toString() + "-" + $theDateTimeObject.month.toString() +"-"+ 
$theDateTimeObject.day.toString() + " " + $theDateTimeObject.Hour.toString() + ":" +$theDateTimeObject.Minute.toString() + ":" + $theDateTimeObject.Second.toString()
Sign up to request clarification or add additional context in comments.

1 Comment

Cheers, that was (almost) perfect. The only problem was that it missed the leading 0 on the month, so it had 9 instead of 09. I got round this by creating each section (day,month etc.) first, then checking the length (-lt 2), and adding the 0, before constructing the final date.
1

The identical answer to your original input is this:

$a = "19/09/2014 22:41:27"
$d = [datetime]::ParseExact($a, "dd/MM/yyyy HH:mm:ss", $null)
$e = "{0:yyyymmddhhmmss}" -f [datetime]$d

It was having an error trying to convert hour 22 as a 12 Hour format.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.