How to get the previous hour time with format in powershell? - powershell

I need to find the previous hour time with formatting with PS:
I need the below format:
"yyyy-MM-dd-HH:mm:sstt")
I can use the below code to get the date and time in this format:
(Get-Date -Format "yyyy-MM-dd-HH:mm:sstt")
2019-09-17-08:45:27AM
I need to get the previous hour time but in the above format
I know how to get the last hour time :
(Get-Date).AddHours(-1)
How can i get the previous hour time with a combination of the above
Format?

Using -f, the format operator, as shown in Ivan Mirchev's helpful answer is definitely an option, and -f is a great general-purpose formatting option to know about, for any data type.
However, in your particular case there is a simpler solution, because the .ToString() method of [datetime] instances directly accepts a format string:
(Get-Date).AddHours(-1).ToString('yyyy-MM-dd-HH:mm:sstt')

You may try using the format operator:
"{0:yyyy-MM-dd-HH:mm:sstt}" -f (get-date).AddHours(-1)
more details: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-6#format-operator--f
Hope it helps! :)

Related

Unix string to date conversion, what is wrong

I know the topic has already emerged and some of the posts give a good summary like the one here: Convert string to date in bash . Nevertheless, I encounter a problem presented below with an example I should solve:
date +'%d.%m.%y' works as desired and returns 05.12.20 but the inverse operation I should use to convert strings to date fails:
date -d "05.12.20" +'%d.%m.%y'
date: invalid date ‘05.12.20’
and this is exactly what I need. The Unix date formatting I have also checked on https://www.cyberciti.biz/faq/linux-unix-formatting-dates-for-display/ but it seems to be in line with that. What is the problem? I also tried to supply time zone indicators like CEST but they did not solve the problem.
Try
date -d "05-12-20" +'%d.%m.%y'
UNIX date expects either - or / as a date separator.
However, if your input really must be in the format "05.12.20" (i.e. using .), then you can convert it to the format expected by UNIX date:
date -d `echo "05.12.20" | sed 's/\./-/g'` +'%d.%m.%y'

How to format Get-Date Day as 2 digits in Powershell

I try to get the Day as a two digit number out of Get-Date in PowerShell.
When I try (Get-Date).Day the result will be for example 6 but I want to have it as 06. Also for the month.
How can this be done?
I have already tried things like (Get-Date).Day.ToString("dd") but it doesn't work.
Using ToString() and supplying date formatters (e.g. "yyyy" or "dd") will only work on dates. By accessing .Day or .Year, the operation is instead attempted on an integer, which will fail.
Try (for the day):
(Get-Date).ToString("dd")
...and (and for the month):
(Get-Date).ToString("MM")
See here for custom formatting of dates using ToString()

Cannot convert this string to Date object in Powershell

I've been struggling with this for some time now and I've tried everything I could find but, have yet to be successful. I need to convert this string to a Powershell date object:
20180802 16:30:10
Everytime I try ParseExact, it's saying that it doesn't recognize the string as a valid date/time format.
Following works perfectly:
[DateTime]::ParseExact('20180802 16:30:10', 'yyyyMMdd HH:mm:ss', [CultureInfo]::InvariantCulture)
I bet your problem is 24 hour format.
Pawel Dyl's helpful answer is the correct and robust solution.
Just to offer a shortcut that may be of interest in similar situations where only a simple textual reformatting is needed in order for a [datetime] cast to recognize a string containing a date/time representation:
Transforming 20180802 16:30:10 to 2018-08-02 16:30:10 would work:
PS> [datetime] ('20180802 16:30:10' -replace '^(\d{4})(\d{2})', '$1-$2-')
Thursday, August 2, 2018 4:30:10 PM # sample output on a US-English system
Note that a [datetime] cast in PowerShell uses the invariant culture, as PowerShell does in many contexts.

Powershell - Adding milliseconds to timestamp

I am trying to create a timestamp string in the format:
yyyymmddhhmmssfff
where f is milliseconds.
Example: 20171013180359235
So far I have
[string]$Date = Get-Date -UFormat "%Y%m%d%H%M%S"
With this I get only up to the seconds. I know if I add %l to the end I get a precision of 2 milliseconds, but I am one short. Is there any way to describe how precise I can choose the milliseconds. Thanks
Using the .tostring() method of the datetime object:
(get-date).ToString('yymmddhhmmssfff')
171513121549340
I use this for some of my work (think, naming files): Get-Date -Format 'DyyyyMMddThhmmsstt.fffffff'. The capital D is for Date and the capital T for time. Perhaps this is helpful!
D20171013T101807AM.8629943

How do I check if a date in format "yyyymmdd" is a weekday or not?

My program accepts date in the format of "yyyymmdd", I don't know how to check if it's a weekday or not. I've seen ppl using $(date +%u) -gt 5 or "$(date +%a)" in Sat|Sun echo "weekend" in other threads, but that ${date} is like Tue Nov 22 14:16:35 EST 2011 I guess. So is there a good way to convert "yyyymmdd" to ${date} format? Or is there a simple way to check if "yyyymmdd" is a weekday or not? Any language is fine. Thanks.
Any language? In Java I'd use SimpleDateFormat or Joda Time's DateTimeFormatter. In C# I'd either use DateTime.ParseExact or Noda Time's LocalDatePattern. In all of these cases, the result is a value which can be asked for things like the day of the week.
In Python I suspect you want datetime.strptime, e.g.
date = datetime.strptime(text, "%Y%m%d")
day = date.weekday()
if day < 5 # Monday(0) to Friday(4)
# Do something here
This is completely untested, however...
Normally, in a typed language (like Java, C# or Python), you'd 1) initialize your "time" to a language-specific "timedate" type, then 2) get the 'day-of-week" from some method of that time.
It looks like you're using Bourne shell. Which is an untyped language, with no native date/time functions.
Here's one possible solution:
http://unix.ittoolbox.com/groups/technical-functional/shellscript-l/day-of-week-bash-script-2018531
Here are several time/timing related things you can do in the (Linux) Bourne shell:
http://tldp.org/LDP/abs/html/timedate.html