-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertTo-SapDate.ps1
More file actions
67 lines (54 loc) · 1.77 KB
/
Copy pathConvertTo-SapDate.ps1
File metadata and controls
67 lines (54 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#Requires -Version 5.1
<#
.SYNOPSIS
Normalises m/d/y style dates into the yyyyMMdd form SAP fields expect.
.DESCRIPTION
PowerShell port of src/vbs/DateFormatCustom.vbs. Accepts "/", "-" and "." as
the separator, tolerates a trailing "h:m:s", and zero pads month and day.
Unparseable input is a non terminating error, so a whole column can be piped
through without one bad row killing the run.
.PARAMETER InputDate
The date text. Accepts pipeline input.
.PARAMETER Separator
Separator for the output. Default "" gives yyyyMMdd.
.EXAMPLE
'6/21/2019 13:05:00' | .\ConvertTo-SapDate.ps1
20190621
.EXAMPLE
Import-Csv .\export.csv | ForEach-Object { $_.Date | .\ConvertTo-SapDate.ps1 -Separator '-' }
#>
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipeline)]
[AllowEmptyString()]
[string[]]$InputDate,
[string]$Separator = ''
)
begin {
Set-StrictMode -Version Latest
# m/d/y is the order the AAE export produces; the year may be 2 or 4 digits.
$formats = @(
'M/d/yyyy', 'M/d/yy',
'M-d-yyyy', 'M-d-yy',
'M.d.yyyy', 'M.d.yy'
)
}
process {
foreach ($item in $InputDate) {
$datePart = ($item -split '\s+', 2)[0].Trim()
if ([string]::IsNullOrEmpty($datePart)) { continue }
[datetime]$parsed = [datetime]::MinValue
$ok = [datetime]::TryParseExact(
$datePart,
$formats,
[Globalization.CultureInfo]::InvariantCulture,
[Globalization.DateTimeStyles]::None,
[ref]$parsed
)
if (-not $ok) {
Write-Error "Not a recognised m/d/y date: '$item'"
continue
}
$parsed.ToString("yyyy'$Separator'MM'$Separator'dd", [Globalization.CultureInfo]::InvariantCulture)
}
}