Skip to content

Instantly share code, notes, and snippets.

@JFFail
Created December 17, 2015 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JFFail/2f6cfa6671f7f2f4699d to your computer and use it in GitHub Desktop.
Save JFFail/2f6cfa6671f7f2f4699d to your computer and use it in GitHub Desktop.
Solution To Reddit Daily Programmer #245 Easy - Date Dilemma
#https://www.reddit.com/r/dailyprogrammer/comments/3wshp7/20151214_challenge_245_easy_date_dilemma/
#Solution to Reddit Daily Programmer 245 Easy.
#Function to parse from the user's specified format into a standard one.
#Void, dumps to STDOUT.
function ParseDate
{
param (
$UserFormat
)
#Make an array to hold the values.
$splitValues = @()
#Check how the items are separated and split accordingly.
if($UserFormat.Contains(" ")) {
$splitValues = $UserFormat.Split(" ")
} elseif($UserFormat.Contains("-")) {
$splitValues = $UserFormat.Split("-")
} elseif($UserFormat.Contains("/")) {
$splitValues = $UserFormat.Split("/")
}
#Figure out what each part is and concatenate them together.
if($splitValues.Count -gt 0) {
if($splitValues[0].Length -gt 2) {
#We know this is Y M D.
$year = $splitValues[0]
$month = $splitValues[1]
$day = $splitValues[2]
} else {
#If year isn't first, it's M D Y.
$month = $splitValues[0]
$day = $splitValues[1]
$year = $splitValues[2]
}
#Make sure month and day are both two digits.
if($month.Length -lt 2) {
$month = "0$month"
}
if($day.Length -lt 2) {
$day = "0$day"
}
#Make sure the year is 4 digits. Assume anything with two digits is in 20xx.
if($year.Length -lt 4) {
$year = "20$year"
}
#Write it all out.
Write-Output "$year-$month-$day"
} else {
#Print an error if the array is empty for some reason because the splits failed.
Write-Output "Error! Could not parse fields for: $UserFormat"
}
}
#Main code.
#Initialize the input array.
$inputArray = "2/13/15", "1-31-10", "5 10 2015", "2012 3 17", "2001-01-01", "2008/01/07"
#Loop through each item, passing to the function to parse them.
foreach($item in $inputArray) {
ParseDate -UserFormat $item
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment