Thursday, October 5, 2017

#88: Difference between two dates

Based on previous posts, I am writing this article. Dates are interesting elements and in most of the scripts, we need to display reports that reflects difference of dates such as the time consumed in a copy operation or any other task. Such statistical information can only be produced if we know how to manipulate date as data type.

DateTime
DateTime is a data-type which is a .NET Class. This class can store date as data-type and it has several mothods that can help us.

You can declare it by casting.

Example: 
[DateTime]$Date1="01/29/2017"  
[DateTime]$Date2="01/29/2019"  
    
( $Date2 - $Date1 ).Days.ToString().padleft(3,"0") + ":" + ` 
( $Date2 - $Date1 ).Hours.ToString().padleft(2,"0")  + ":" + ` 
( $Date2 - $Date1 ).Minutes.ToString().padleft(2,"0")  + ":" +  ` 
( $Date2 - $Date1 ).Seconds.ToString().padleft(2,"0")
Output: 
730:00:00:00

Explanation: 
The first line declares variable by casting it with DateTime data-type and same is repeated with another variable in second line.

Next four lines would get the difference in days, hours, minutes and seconds. With each line we have using padding so that 1 is shown as 01 and 2 is shown as 02 and so on so forth.

A concatenation is done with colons (:) and days are shown with three padding of zeros while hour, minute and seconds are padded with two zeros. 

Hope you enjoyed this tip!

Thanks for reading the article. Please send your comments if you find any difficulty understanding this tip.

No comments:

Post a Comment

#112: How to handle xml document in Powershell?

 In PowerShell, you can handle XML data using various cmdlets and methods provided by the .NET Framework. Here's a basic guide on how to...