I have this snippet of code that converts a registry value to a date string (originally hex value 2f 04 1e 00 00 00 00 00):
ElseIf (($sepmastersvc)) {
$sepmasterst = [bool]$sepmaster
$sepStatus = $sepmastersvc.status
$SEPVscan = (get-itemproperty "HKLM:SOFTWARE\Wow6432Node\Symantec\Symantec Endpoint Protection\AV") 2> $null
If (!($SEPVscan)) {
$SEPVscanStatus = [bool]$SEPVscan
$SEPDatVer = "N/A"
}
Else {
$SEPVscanStatus = [bool]$SEPVscan
$SEPDatVerY = [string]($SEPVscan.PatternFileDate[0] + 1970)
$SEPDatVerM = ($DateTimeFormat.MonthNames[$SEPVscan.PatternFileDate[1]])
$SEPDatD = [string]$SEPVscan.PatternFileDate[2]
$SEPDatVer = $SEPDatVerY + $SEPDatVerM + $SEPDatD
}
}
I need to get the month number instead of name.
I've found examples of converting a month number to name but can't get it working the other way around.
You can use Get-Date and specify the format. "MM" will retrieve the month in 2 digit number.
get-date -format "MM"
Here is a list of possible formats: https://technet.microsoft.com/en-us/library/ee692801.aspx
I'm not sure what format your date is, but from what I can see, you could try
Get-Date -Date "$SEPDatVerM $SEPDatD $SEPDatVerY" -format "yyyy MM dd"
and that should give you a date formatted as this: for example "2015 03 21"
Related
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>
I have a cmdlet that is expecting an int32 for the date instead of a normalized input.
Set-CTXGroupPolicyConfiguration, RebootScheduleStartDate wants int32-input. For instance, if i enter this into policy manually, it has tomorrow, 1/18/2015 as 132055314. Coming up blank with what that number is even referring to.
This was fun. I found this Citrix Support site where they describe how the dates are stored as a dword (uint32) value in registry. The dword-value is created like:
Date is split into year, month and date
Each value is converted to hex-value
The hex-values are combined (16bit year, 8bit month, 8bit day) in the pattern yyyyMMdd
The combined hex-value is converted to decimal
I've created a couple of functions to convert the dates for you:
function ConvertFrom-DwordDate([int32]$DwordValue) {
#Ex. $DwordValue = 132055314
#Convert to hex with 8 chars (16bit year + 8bit month + 8bit day)
$hex = $DwordValue.ToString('X8')
#Ex. $hex = 0x07df0112 = 0x07df(year) 0x01 (month) 0x12 (day)
#Convert to date string
$datestring = '{0:D4}\{1:D2}\{2:D2}' -f [convert]::ToUInt32($hex.Substring(0,4),16), [convert]::ToUInt32($hex.Substring(4,2),16), [convert]::ToUInt32($hex.Substring(6,2),16)
#Convert to datetime and output
$datetime = [datetime]::ParseExact($datestring,'yyyy\\MM\\dd',$null)
#Output
$datetime
}
function ConvertTo-DwordDate([datetime]$Date) {
#Convert to combined hex
$combinedhex = '{0:X}{1:X2}{2:X2}' -f $Date.Year, $Date.Month, $Date.Day
#Convert to decimal
$decimal = [convert]::ToUInt32($combinedhex,16)
#Ouput
$decimal
}
ConvertTo-DwordDate -Date (Get-Date).AddDays(1)
132055314
ConvertFrom-DwordDate -DwordValue 132055314
søndag 18. januar 2015 00.00.00
I know this is a ridiculously old post but it's the top response on Google for "powershell get-date as int".
$DateInt = [Int]((Get-Date).addDays(-100).ToString('yyyyMMdd'))
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")
I need to make an PHP operation with dates with format ISO 8601. Something like:
$starDate = 2012-03-20T00:00:00+01:00; //20 March 2012
$endDate = 2012-04-01T00:00:00+02:00; // 1 April 2012
$diff = $starDate - $endDate; //Result should be: 13
Using this code $diff get a value of cero.
Try this :
function date_diff($date1, $date2)
{
$s = strtotime($date2)-strtotime($date1);
$d = intval($s/86400)+1;
return "$d";
}
Source : http://forum.hardware.fr/hfr/Programmation/PHP/php-calculer-nombre-sujet_30415_1.htm
I took this piece from an unencrypted .DAT file:
Code:
00 e1 27 17 6f e6 69 c0
Which translates to 63,374,851,375,000,000 in decimal. The units for the number are microseconds.
And this huge number cannot bypass the 1st January 1970 00:00:00 format; such a format that most converters use today.
So, yes. Is there such a converter that uses the 1st January of the year 1 format? Or how shall I make one?
And by the way, a timestamp is both date and time.
Thanks in advance!
You do not say what language are you using, if it is a .NET language, you can use: http://msdn.microsoft.com/en-us/library/z2xf7zzk.aspx for that constructor the input is in nanoseconds (are you sure that your number is in milliseconds and not in nanoseconds?).
If you are sure it is in milliseconds, the conversion to nanoseconds should be easy: 1 millisecond = 1 000 000 nanoseconds.
But I have the feeling that those are nanoseconds and not milliseconds...
Now that you have told us that it is in microseconds:
C# Example from decimal to yyyy dd MM hh:mm:ss
long microseconds = 63370738175000000;
long ticks = microseconds * 10;
DateTime timestamp = new DateTime(ticks);
Console.WriteLine(timestamp.ToString("yyyy dd MM hh:mm:ss"));
It prints:
2009 20 02 02:49:35
The other way around from yyyy dd MM hh:mm:ss to decimal
String dateString = "2009 20 02 02:49:35";
DateTime timestamp = DateTime.ParseExact(dateString, "yyyy dd MM hh:mm:ss",CultureInfo.CurrentCulture);
long ticks = timestamp.Ticks;
long microseconds = ticks / 10;
Console.WriteLine(microseconds);
It prints:
63370694975000000
And if you want it in hexadecimal just write:
Console.WriteLine(microseconds.ToString("X"));
Then it will print:
E1234FB3278DC0
If you want the answer in another programming language, please add that to you question.
In JAVA in order to convert microseconds into java.sql.Timestamp:
public static Timestamp getTimestampFromMicros(long pMicros) {
long millis = TimeUnit.MICROSECONDS.toMillis(pMicros);
long shaaritInMicros = pMicros - TimeUnit.MILLISECONDS.toMicros(millis);
Timestamp ts = new Timestamp(millis);
long nanos = ts.getNanos() + TimeUnit.MICROSECONDS.toNanos(shaaritInMicros);
ts.setNanos((int)nanos);
return ts;
}
Use below Java code to covert microseconds to date and time,
long msec = microseconds * 1/1000;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
dateFormat.format(msec);
Which will returns,
2016-01-27 03:41:12