Formatting PowerShell Get-Date inside string - powershell

I can't get my head around how formatting a datetime variable inside a string works in PowerShell.
$startTime = Get-Date
Write-Host "The script was started $startTime"
# ...Do stuff...
$endTime = Get-Date
Write-Host "Done at $endTime. Time for the full run was: $( New-TimeSpan $startTime $endTime)."
gives me the US date format while I want ISO 8601.
I could use
$(Get-Date -Format u)
but I want to use $endTime to make the calculation of the timespan correct.
I have tried all permutations of $, (, ), endTime, -format, u, .ToString(...) and .ToShortDate(), but the one that works.

"This is my string with date in specified format $($theDate.ToString('u'))"
or
"This is my string with date in specified format $(Get-Date -format 'u')"
The sub-expression ($(...)) can include arbitrary expressions calls.
Microsoft Documents both standard and custom DateTime format strings.

You can use the -f operator
$a = "{0:D}" -f (get-date)
$a = "{0:dddd}" -f (get-date)
Spécificator Type Example (with [datetime]::now)
d Short date 26/09/2002
D Long date jeudi 26 septembre 2002
t Short Hour 16:49
T Long Hour 16:49:31
f Date and hour jeudi 26 septembre 2002 16:50
F Long Date and hour jeudi 26 septembre 2002 16:50:51
g Default Date 26/09/2002 16:52
G Long default Date and hour 26/09/2009 16:52:12
M Month Symbol 26 septembre
r Date string RFC1123 Sat, 26 Sep 2009 16:54:50 GMT
s Sortable string date 2009-09-26T16:55:58
u Sortable string date universal local hour 2009-09-26 16:56:49Z
U Sortable string date universal GMT hour samedi 26 septembre 2009 14:57:22 (oups)
Y Year symbol septembre 2002
Spécificator Type Example Output Example
dd Jour {0:dd} 10
ddd Name of the day {0:ddd} Jeu.
dddd Complet name of the day {0:dddd} Jeudi
f, ff, … Fractions of seconds {0:fff} 932
gg, … position {0:gg} ap. J.-C.
hh Hour two digits {0:hh} 10
HH Hour two digits (24 hours) {0:HH} 22
mm Minuts 00-59 {0:mm} 38
MM Month 01-12 {0:MM} 12
MMM Month shortcut {0:MMM} Sep.
MMMM complet name of the month {0:MMMM} Septembre
ss Seconds 00-59 {0:ss} 46
tt AM or PM {0:tt} ““
yy Years, 2 digits {0:yy} 02
yyyy Years {0:yyyy} 2002
zz Time zone, 2 digits {0:zz} +02
zzz Complete Time zone {0:zzz} +02:00
: Separator {0:hh:mm:ss} 10:43:20
/ Separator {0:dd/MM/yyyy} 10/12/2002

Instead of using string interpolation you could simply format the DateTime using the ToString("u") method and concatenate that with the rest of the string:
$startTime = Get-Date
Write-Host "The script was started " + $startTime.ToString("u")

Related

Trouble with converting to Datetime object

I have the below data which is an object type variable named $timestamps
Sat Jan 15 16:21:24
Sat Jan 15 01:31:22
Fri Jan 14 20:58:09
Fri Jan 14 20:51:02
I'm having trouble converting it to Datetime object because of the weird date format. How would you handle this?
I would like it as a datetime object because I plan to convert from current (UTC) to EST.
TIA
You can use the the ParseExact() method provided by the [datetime] class for this:
[datetime]::ParseExact('Fri Jan 14 20:58:09','ddd MMM dd HH:mm:ss',$null)
# returns a - datetime - object of:
# Friday, January 14, 2022 8:58:09 PM
dd - for the day.
MM - for the month.
HH - for the hour - Capitalized for the 24 hour time format.
mm - for the minutes.
ss - for the seconds.
Edit: as suggested by mklement0, we can use [cultureinfo]::InvariantCulture to make the parsing specific to an English date time format. Also, changing dd to d as a more robust solution for days without 2 digits; which should cover both singular, and double digit days.
Seeing $timestamps is an array of strings, you can use a loop (of your choice - in this case the Foreach-Object cmdlet) to iterate through each string parsing the text to return a datetime object:
$timestamps | ForEach-Object {
$culture = [cultureinfo]::InvariantCulture
$format = 'ddd MMM d HH:mm:ss'
$date = [datetime]::ParseExact($_,$format,$culture,'AssumeUniversal, AdjustToUniversal')
[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId($date, 'Eastern Standard Time')
}
Using 'AssumeUniversal, AdjustToUniversal' ensures a UTC output.
Assuming from your comment that you'd like to do a conversion to Eastern Time, passing the newly created datetime object to [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId() with an argument of the desired time zone, you can get your result in the new time zone.
When using $null, the CultureInfo object that corresponds to the current culture is used.
The DateTime.ParseExact() method is probably what you're looking for.
PS C:\TEMP>$timestamp = 'Sat Jan 15 16:21:24'
PS C:\TEMP>$format = 'ddd MMM dd HH:mm:ss'
PS C:\TEMP>[datetime]::ParseExact($timestamp, $format, $null)
Saturday, January 15, 2022 04:21:24 PM
PS C:\TEMP>

How can I set Date format when use power shell to generate date and save to batch variable?

I use this command in batch for generate curentdate -1 and save it to variable in batch but How can I put format in ToString() I already use ' and "
for /f "tokens=*" %a in ('powershell "$date = Get-Date; $date=$date.AddDays(-1);$date.ToString();"') do set var=%a
You can use :
for /f "tokens=*" %a in ('powershell "$date = Get-Date; $date=$date.AddDays(-1);$date.ToString('yyyy:MM:dd');"') do set var=%a
Here are the specificators :
Spécificator Type Example Output Example
dd day dd 10
ddd Name of the day ddd Jeu.
dddd Complet name of the day dddd Jeudi
f, ff, … Fractions of seconds fff 932
gg, … position gg ap. J.-C.
hh Hour two digits hh 10
HH Hour two digits (24 hours) HH 22
mm Minuts 00-59 mm 38
MM Month 01-12 MM 12
MMM Month shortcut MMM Sep.
MMMM complet name of the month MMMM Septembre
ss Seconds 00-59 ss 46
tt AM or PM tt ““
yy Years, 2 digits yy 02
yyyy Years yyyy 2002
zz Time zone, 2 digits zz +02
zzz Complete Time zone zzz +02:00
: Separator hh:mm:ss 10:43:20
/ Separator dd/MM/yyyy 10/12/2002

how can i get the day of the week for a particular given date in Matlab

As today is Wednesday with date June 8, 2016. how can i write a code to get the day of given dates:
like what day is Nov 29
I'm trying to create a struct with
date
day
month
with month and date as input
Use the builtin weekday() function:
>> [num, name] = weekday('08-Jun-2016')
num =
4
name =
Wed
>> [num, name] = weekday('29-Nov-2016')
num =
3
name =
Tue
In addition to the weekday function, you can use the DDD or DDDD formats in the datestr function, like this:
datestr('08-Jun-2016','DDD') %Returns the string 'Wed'
datestr('08-Jun-2016','DDDD') %Returns the string 'Wednesday'
Or, to use a more practical format
datestr('08-Jun-2016','DDDD, mmmm DD, yyyy')
% Returns the string: 'Wednesday, June 08, 2016'

AppleScript countdown

I want to have a string that counts down from current time to alarm time.
I've manage to figer out how to get the current time and how to set the alarm time.
The problem I'm having is that when I take current time - alarm time it gives me a numer witch I then need to format back to a hh:mm:ss string.
i've got this.
set alarmHour to 23
set alarmMinute to 00
set theDate to the current date
set the hours of theDate to alarmHour
set the minutes of theDate to alarmMinute
set the seconds of theDate to 0
theDate
set countdown to theDate - (current date)
set ss to countdown / 60
at this point it gives me 22.283333333333 witch i now need to convert to hh:mm:ss and then put them into a sting that give me 00:22:00
UPDATE:
in swift you have % you can use
countDownTime = (formatterInteger - timeControlInteger)
let interval = Int(countDownTime)
let seconds = interval % 60
let minutes = (interval / 60) % 60
let hours = (interval / 3600)
but how to you do this in applescript?
Answer to second question:
is there a way to format strings like in swift? like
String(format:"%02d",absHour) – Mathias Halén
Yes, but you need to use the Satimage.osax scripting addition, available for free at:
Satimage AppleScript Additions
Satimage strftime() -- Date/Time Format Function
strftime v : format a date using a specification string like in the C
function strftime.
strftime date or list of date
into string : the formatting string. To obtain ISO 8601 dates, use
"%FT%TZ" or "%GW%V-%uT%TZ" (using the 'with GMT' parameter)
[GMT boolean] : if true, output date as GMT. Default: false, the ouput
date is local.
→ string : the formatted date
EXAMPLE: strftime (current date) into “%x” RETURNS: 07/22/14
"%a, %b %d, %Y" RETURNS: Tue, Jul 22, 2014
set d to current date
-- some ISO 8601 formats:
strftime d into "%FT%T%z"
-- "2007-01-15T16:10:56+0100"
strftime d into "%GW%V-%uT%T%z"
-- "2007W03-1T16:10:56+0100"
--if you need to store the date d as UTC:
strftime d into "%FT%TZ" with GMT
-- "2007-01-15T15:10:56Z"
strftime d into "%a, %b %d, %Y %H:%M:%S %z"
-- "Mon, Jan 15, 2007 16:10:56 +0100"

formatting date from twitter response Zend Framework

im trying to formatting the date field 'created_at' from Twitter API response with Zend_Date. I want output the date like this:
21 of July of 2009, 12:30:00 (for example)
What format is this?:
Fri Oct 23 15:47:42 +0000 2009
thanks a lot
I've had the best luck just doing
$d = new Zend_Date(strtotime($input));
$twitter_format_out = $d->toString('EEE MMM dd HH:mm:ss Z YYY');
These date are not looking a standard format. Therefore, you have to create a format with the right constants (see them here).
Your first example (21 of July of 2009, 12:30:00):
$format = "d ' of ' MMMM ' of ' YYYY, h:mm:ss";
Your second example (Fri Oct 23 15:47:42 +0000 2009):
$format = "EEE MMM d h:mm:ss Z YYYY";
This formats you can use both for importing a date
$date = new Zend_Date($string, $format);
Or for outputting
$date->toString($format);
Look in the manual for locale support etc.