How can I get the current date in an Azure Pipeline YAML file to use ase a variable?
Asked Answered
M

2

15

I'm trying to inject a useful version number into my ASP Core application which I'm building and deploying using an Azure DevOps pipeline.

- script: dotnet publish -c $(buildConfiguration) -p:Version=2022.06.21 -p:SourceRevisionId=$(Build.SourceVersion)

But I cannot for the life of me work out how to get the date into a variable where I can actually use it. Which is pretty remarkable really since the current date (with some other fluff appended) is what DevOps itself uses for the default build number.

The documentation is horrendous. How do I do this?

Monochrome answered 21/6, 2022 at 10:55 Comment(1)
There is no predefined variable containing the current date, but you can add a custom script to get the current date (i.e. with PowerShell), and write it to an own variable, see the docs for more detailPiccaninny
P
25

With the format expression you can transform the pipeline.startTime into a formatted date. In your case, define the variable like the following:

variables:
  currentDate: $[ format('{0:yyyy}.{0:MM}.{0:dd}', pipeline.startTime) ]

Then use the variable like the following:

- script: dotnet publish -c $(buildConfiguration) -p:Version=$(currentDate) -p:SourceRevisionId=$(Build.SourceVersion)
Piccaninny answered 21/6, 2022 at 11:30 Comment(5)
This sorted me out, although I found the syntax in your answer resulted in a format error, the following expression though did work. currentDate: $[format('{0:yyyy}.{0:MM}.{0:dd}', pipeline.startTime)]Monochrome
@Monochrome thanks for sorting this out, I did not test this. Will update the answer.Piccaninny
Note that this doesn't appear to be the actual pipeline start time, but when the agent started. Meaning it will give you different results per job. developercommunity.visualstudio.com/t/…Dissatisfaction
Can you add hours and minutes too? - "hh:mm:ss"Rapeseed
@Rapeseed sure, just check the doc I linked. You can use any .NET date format specifiers. For hours and minutes you can use HH:mmPiccaninny
N
0

It can also be solved using below YAML code:

- name: CurrentDateTime
  value: $(Get-Date -Format yyyy.MM.dd_HHmmss)

Of course, you can adjust the above format as per your need.

and then it can be used via macro syntax as $(CurrentDateTime)

Refer to this developer community post: https://developercommunity.visualstudio.com/t/how-to-get-formatted-date-into-variable-in-a-azure/824760

Nomology answered 15/4 at 6:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.