how to compare two custom dates in powershell v2.0 - powershell

Is it possible to compare 2 custom dates. Am trying check if variables hold date1 is lessthan date2, if so, report saying date1 is older date.
I getting both dates from a. date1 from log file and date2 from application itself
now, both date1 and date2 are in required format ie,
$Date1 = Tue,Aug 16, 2016 12:40:03
$Date2 = Mon,Aug 22, 2016 16:33:02
my next step is compare these 2 dates and report if date1 is older date compare to Date2, which I don't know how to proceed.. Any help/ideas is much appreciated.
Thanks to Pete and Ansgar Wiechers
updated working Code :
$Date1DateTime = [DateTime]::ParseExact($Date1,'ddd,MMM d, yyyy, HH:mm:ss',[Globalization.CultureInfo]::InvariantCulture); $Date2DateTime = [DateTime]::ParseExact($Date2,'ddd,MMM d, yyyy, HH:mm:ss',[Globalization.CultureInfo]::InvariantCulture); $Date1DateTime -lt $Date2DateTime

You can only compare date strings if the string sort order is the same as the date sort order. For instance, date strings in ISO format are comparable:
2016-08-16T12:40:03
2016-08-22T16:33:02
Date strings in your custom format are not, because T comes after M, but August 16 should actually come before August 22:
Tue,Aug 16, 2016 12:40:03
Mon,Aug 22, 2016 16:33:02
If you don't have the date strings in ISO format it's usually better to parse them into actual DateTime values (as #PetSerAl suggested), particularly if your reference value is originally a DateTime anyway.
$fmt = 'ddd,MMM d, yyyy, HH:mm:ss'
$culture = [Globalization.CultureInfo]::InvariantCulture
$Date1 = Get-Date $LogFileDate
$val = (b2b.exe -readparams $param | Select-Object -Skip 1 -First 1) -split '='
$Date2 = [DateTime]::ParseExact($val[1], $fmt, $culture)
if ($Date1 -lt $Date2) {
...
}

Related

Powershell - Get date from week and weekday

I have a file containing 'year', 'week-number', and 'weekday', (example - '2022', '42', '4',) 42 represents week 42 of 2022, and the 4 represents tuesday. A 7 would represent sunday.
The first week is to be considered the first days until sunday, regardless if it is 7 days or not. Same principle for the last week. That week can also contain fewer than 7 days.
How can i translate this to a date like 'yyyyMMdd'?
Thanks
Note:
The following uses .NET's System.DayOfWeek enumeration to identify weekdays, which means that Sunday is 0, Monday is 1, ..., and Saturday is 6.
If your weekday-numbering scheme differs (which is what it sounds like), you'll have to map it onto the above.
# Convert the strings (representing CSV input) to numbers.
[int] $year, [int] $week, [int] $weekday = '2022', '42', '4'
# The day of the week you consider the start of a calendar week.
$startOfWeekDay = [DayOfWeek]::Monday
# Calculate the start of calendar week 1 for the given year:
# The Monday on or preceding Jan 1
# Note: This date may therefore fall into the previous year.
$Jan1 = [datetime]::new($year, 1, 1)
$StartOfWeek1 = $Jan1.AddDays(-((7 + $Jan1.DayOfWeek-$startOfWeekDay) % 7))
# Calculate the start of the target calendar week.
$StartOfTargetWeek = $StartOfWeek1.AddDays($week * 7)
# Calculate the target date by determining the desired weekday
# inside the target week.
$TargetDate = $StartOfTargetWeek.AddDays((7 + $weekday-$startOfWeekDay) % 7)
$TargetDateString = $TargetDate.ToString('yyyyMMdd')
# Output *for display* both the intermediate results and the final one.
[pscustomobject] #{
Jan1 = ($Jan1 | Out-String).Trim()
StartOfWeek1 = ($StartOfWeek1 | Out-String).Trim()
StartOfTargetWeek = ($StartOfTargetWeek | Out-String).Trim()
TargetWeekDay = [DayOfWeek] $weekday
TargetDate = ($TargetDate | Out-String).Trim()
TargetDateString = $TargetDateString
} | Format-List
Output:
Jan1 : Saturday, January 1, 2022 12:00:00 AM
StartOfWeek1 : Monday, December 27, 2021 12:00:00 AM
StartOfTargetWeek : Monday, October 17, 2022 12:00:00 AM
TargetWeekDay : Thursday
TargetDate : Thursday, October 20, 2022 12:00:00 AM
TargetDateString : 20221020

To compare the day , date , timestamp of two lines in file and output the latest day,date,timestamp

I have below lines from two different file having day , date ,timestamp. I need to output the line with latest timestamp.
The lines of one file :
Tue 31/12/2000 17:13:29.83 - file copied
And another file content is :
Sun 17/07/1996 12:11:14.84 - drivers updated
The output must be
Tue 31/12/2000 17:13:29.83 - file copied
How can we compare timestamp?
To parse out the date from these strings you can do:
# get the date and time from the string, remove the dayname as it is incorrect for that date
$dateString = ("Sun 31/12/2000 17:13:29.83 - file copied" -split '-')[0].Substring(4).Trim()
$date1 = [datetime]::ParseExact($dateString, 'dd/MM/yyyy HH:mm:ss.ff', [CultureInfo]"en-US")
# do the same for the date in the second file and call that $date2
Then simply compare the dates using
$theDateYouWant = if ($date1 -gt $date2) { $date1 } else { $date2 }
By stripping off the dayname, you can use $null or [cultureinfo]::InvariantCulture instead of [CultureInfo]"en-US"

Groovy Date code producing unexpected output

Why is below code producing output like this ?
String oldDate = "2013-12-05 01:34:54.270"
Date date = Date.parse( 'yyyy-mm-dd hh:mm:ss', oldDate )
Output : Sat Jan 05 01:34:54 EST 2013
When it should simply produce December 5 as the date in the output ? In fact in the original string whatever month I put in it produces the exact same output.
The problem is your date format isn't correct. mm is for minutes where MM is for month. So it should be:
String oldDate = "2013-12-05 01:34:54.270"
Date date = Date.parse( 'yyyy-MM-dd hh:mm:ss', oldDate )
You can find out more from the Java API docs for SimpleDateFormat.

Using Powershell how do you get the weekday number?

Using a Powershell date object how do you get the day number of the week, 0 to 6 where 0 would be Sunday and 6 would be Saturday. I know that I can get the day name with the code below but how do I get the number as there is no DayNumberOfWeek or equivalent property?
(Get-Date).DayOfWeek
I suppose I could use the day name from the code above in a switch statement to convert it to a number but that doesn't seem to be very eloquent.
like this:
( get-date ).DayOfWeek.value__
I suggest for the future to investigate what properties an object in this way:
( get-date ).DayOfWeek | gm -f # gm is an alias for get-member
Well, the DayOfWeek property of a DateTime is not a string but rather a DayOfWeek enum, so the shortest answer is probably
[Int] (Get-Date).DayOfWeek # returns 0 through 6 for current day of week
Or
[Int] [DayOfWeek] "Wednesday" # returns 3
Get-Date -UFormat %u
will return formated date.
check http://technet.microsoft.com/en-us/library/hh849887.aspx for more fomats
On Friday the 17th:
(get-date).DayOfWeek.value__
Returns 5
(Get-Date).DayOfWeek
Returns Friday
(Get-Date).Day
Returns 17

Powershell variable interrogation of date & time difference

Morning All,
I have a variable as follows: $machines = $user2,$name,$serial,$purchased
sample data stored in $machines is:
User1,
Laptop1,
xyz1234,
01/01/2010
I am wanting to create a new variable called $tobereplaced containing all of the records in $machines with a date greater than 4 years old from todays date.
the fuzzy logic code for this im expecting to be someting like $tobereplaced = $machines.$purchased | where {$_$purchased = -getdate > 4 years} etc etc but i cant quite figure it out.
Assistance would be greatly appreciated.
Thanks
$fourYearsAgo = (Get-Date).AddYears(-4)
$tobereplaced = $machines | Where-Object { (Get-Date $_[-1]) -le $fourYearsAgo }
Convert the date as DateTime and compare it against a date four years ago. Like so,
# Assuming $m[3] contains the timestamp, parse it as a DateTime and compare
# against a date four years ago.
if([DateTime]::Parse($m[3]) -le [DateTime]::Now.AddYear(-4)) {
$tobereplaced += $m
}
Depending on your locale, you might need to tell [DateTime]::Parse() how to parse the date. Is 01/12/2010 1st of December, 2010 or 12th January, 2010?