All about Datetime - UiPath

Hi All,

My recent post on datatable [All About Datatable- UiPath] (All about Datatable - UiPath) was received well in forum with great feedbacks and many suggested to provide some tutorial on topics which are discussed often in our forum

In regards to that I would like to share the commonly used expression for DATETIME conversion

Let’s get started one by one

1. Get Current Date in string format

Datetime.Now.ToString()

(Output - string type - “dd/MM/yyyy hh:mm:ss”)

**To get only current datetime as a variable **

Datetime.Now

(Output - Datetime variable)

2. Get different formats of datetime as string type

Get current day alone - numerical terms

Datetime.Now.ToString(“dd”)

** Get current day - full text**

Datetime.Now.ToString(“dddd”)

Get Current month - full name

Datetime.Now.ToString(“MMMM”)

Get current month - first three characters

Datetime.Now.ToString(“MMM”)

Get current month - numerical value

Datetime.Now.ToString(“MM”)

Get current year - full year

Datetime.Now.ToString(“yyyy”)

Get current year - last two characters

Datetime.Now.ToString(“yy”)

Get current time - in 12 hrs format

Datetime.Now.ToString(“hh:mm:ss”)

get current time - in 24 hours format

Datetime.Now.ToString(“HH:mm:ss”)

Get current hour alone - 12 hrs format

Datetime.Now.ToString(“hh”)

Get current hours alone - 24 hours format

Datetime.Now.ToString(“HH”)

Get Current minutes

Datetime.Now.ToString(“mm”)

Get current seconds

Datetime.Now.ToString(“ss”)

3. Get current Datetime as string with TIMEZONE

Datetime.Now.ToString(“dd/MM/yyyy hh:mm:ss K”)

4. Get current Datetime with AM / PM

Datetime.Now.ToString(“dd/MM/yyyy hh:mm:ss tt”)

5. Convert a string to Datetime

If input is Strinput = “12/02/2022”

with Convert.ToDatetime method

var_datetime = Convert.ToDatetime(Strinput.ToString)

with Datetime.Parse method

var_datetime = Datetime.Parse(Strinput.ToString)

with Datetime.ParseExact method

var_datetime = Datetime.ParseExact(Strinput.ToString, “dd/MM/yyyy”, System.Globalization.CultureInfo.InvariantCulture)

In the above last expression dd/MM/yyyy depends on what format the Strinput variable holds
It has to be same as that
So based on what format we find in string input variable mention the same format instead of “dd/MM/yyyy” in last expression

Note : if you want tour above expression as string output type then include .ToString atlast of the expression

Suppose If the input is of full format

Strinput = “23/11/2022 02:20:31 +5:30”

Then to get this as Datetime

var_datetime = Datetime.ParseExact(Strinput.ToString, “dd/MM/yyyy hh:mm:ss K”)

6. Validate whether a Datetime is valid date

type or not

bool_date = DateTime.TryParseExact(strinput.ToString,“MM/dd/yyyy hh:mm:ss”, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, Nothing)

This gives Boolean as output type and validate whether the string input matches with the format mention within double quotes (“MM/dd/yyyy hh:mm:ss”)

7. Convert a String of multiple possible date formats to a Datetime variable

Say you have a date string which can be of different formats for each time it is being used like
“dd/MM/yyyy”, “MM/dd/yyyy”, “dd/yy”

Then have all these possible formats in a array variable named arr_formats

Like this

arr_formats = {“dd/MM/yyyy”, “MM/dd/yyyy”, “dd/yy”}

Then to convert that string as Datetime

var_datetime = DateTime.ParseExact(Strinput.ToString, arr_formats, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None)

8. Convert a string to Datetime of specific culture info

Say Strinput = “12-22-2022”

To get it as German time and details

str_datetime = Datetime.ParseExact(Strinput.ToString, “MM-dd-yyyy”, System.Globalization.CultureInfo.InvariantCulture).ToString(“dd/MM/yyyy”, New CultureInfo(“de-DE”))

We can mention any time zone info along CultureInfo arguments like above

9. Convert DateTime variables between UTC and Local or a specific timezone

Refer this wonderful thread on converting a Datetime to specific timezone

10. Difference in days between two dates

If Strinput = “12-Jan-2022”

int_days = DateDiff(DateInterval.Day, DateTime.ParseExact(Strinput.ToString, "dd-MMM-yyyy", System.Globalization.CultureInfo.InvariantCulture),DateTime.now())

11. Difference in months between two dates

If Strinput = “12-Jan-2022”

int_months = DateDiff(DateInterval.Month, DateTime.ParseExact(Strinput.ToString, "dd-MMM-yyyy", System.Globalization.CultureInfo.InvariantCulture),DateTime.now())

Same for years replace Month as Year in above expression
Like this

If Strinput = “12-Jan-2022”

int_years = DateDiff(DateInterval.Year, DateTime.ParseExact(Strinput.ToString, "dd-MMM-yyyy", System.Globalization.CultureInfo.InvariantCulture),DateTime.now())

12. Get first date of the current month

str_firstdate = New DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString

13. Get Last date of the current month

str_lastedate = New DateTime(now.Year, now.Month, DateTime.DaysInMonth(now.Year, now.Month)).ToString

14. Get last date of previous month

str_lastdate = New DateTime(now.Year,now.Month,1).AddDays(-1).ToString

15. Get first date of the year

str_firstdate = New DateTime(now.Year,1,1).ToString

16. Get last date of the year

Str_lastdate = New DateTime(now.Year,12,31).ToString

17. Calculate business days of a year

Refer this custom component

18. Get next - previous business working day

Refer this custom component

19. Filter DATETIME in excel or a Datatable

When I started learning for filtering Datetime in a datatable, I referred this thread with simple method to do Datetime filteration
Have a view on the sample xaml for more details

20. Add hours to current time

str_datetime = Datetime.Now.AddHours(1).ToString()

add 5 Days

str_datetime = Datetime.Now.AddDays(5).ToString()

add 10 years to current date

str_datetime = Datetime.Now.AddYears(10).ToString()

Same for months as well

21. Minus days from current day

str_datetime = Datetime.Now.AddDays(-1).ToString()

Subtract 5 months from current month

str_datetime = Datetime.Now.AddMonths(-5).ToString()

Subtract 10 years from current year

str_datetime = Datetime.Now.AddYears(-10).ToString()

22. Convert a OADate in excel to a Datetime or string Datetime

Suppose Actual value being entered: ‘43800’ but the required value is “1-Dev-2022” in format “dd-MMM-yyyy”

Then use this in assign activity

str_datetime = DateTime.FromOADate(Convert.ToDouble(Strinput.ToString)).ToString(“dd-MMM-yyyy”)

23. Difference string formats from a Datetime

While converting a Datetime to string apart from user defined string formats there are other string formats obtained from these below methods instead of ToString in Datetime.ParseExact(……).ToString()

.ToOADate()
.ToLongDateString()
.ToShortDateString()
.ToLongTimeString()
.ToShortTimeString()
.ToString()
.ToUniversalTime()
.ToFileTime()
.ToLocalTime()

24. Create a TimeSpan variable with default value initialised in variable panel

TimeSpan var_interval = new TimeSpan(2, 14, 18)

The default value attributed to a TimeSpan variable uses the day.hh:mm:ss format.

25. Convert a string to TimeSpan

If Strinput = “12:20:45”

var_timespan = TimeSpan.Parse(Strinput.ToString)

26. Convert different time values to TimeSpan

If we have time values in milliseconds, hours, days, and in order to convert that to TimeSpan

var_TimeSpan = TimeSpan.FromMilliseconds(1000)
var_TimeSpan = TimeSpan.FromDays(1)
var_TimeSpan = TimeSpan.FromHours(2)
var_TimeSpan = TimeSpan.FromMinutes(30)
var_TimeSpan = TimeSpan.FromSeconds(20)
var_TimeSpan = TimeSpan.FromTicks(10000)

——————————————————————-

Hope this will be helpful :slight_smile:

Questions

For questions on your retrieval case open a new topic and get individual support

Feedback

Share the scenarios and solution or approach used to solve that, here below to this post which would definitely help others looking for similar scenario

Cheers @loginerror @Forum_Moderators_2024 @advanced
@orchestrator

102 Likes
Convert String "dd/MM/yyyy" to String "dd.MM.yyyy"
String is not recognized as a valid datetime - MM/dd/yyyy format is only working
I would like to convert the time format from 12 hours to 24 hours
Regex help tutorial MEGAPOST – Making your first Regex post, Reusable Regex Patterns, Regex Troubleshooting, Sample Workflow and more
Calendar/holidays
DateTime.now command help
Choose current month dynamically
Assign: String '11/1/2022 12:00:11 AM' was not recognized as a valid DateTime
Changing variable date format
Convert dd/mm/yyyy to get the day
How to change the date separator from mm/dd/yyyy to mm.dd.yyyy and add 00:00 in the end?
How to check the previous date
How to split dates in a month with 5 days Interval
DateTime Manipulation - String was not recognized as a valid DateTime
How to get date difference between two date variables? c#
String to Date Converstion
Work days, Weekends and Controlling of Holidays?
How to get date in format "MM/dd/yy"
How to get previous week number of the year
Date to string conversion
Convert to Date Time From String
Getting error while converting String to datetime
String to Date
Scrapping last 4 week data dynamically
Format datetime
Taking date from a string holding the day
String format to date
How to and where to learn Vb.Net Expressions/functions
How to Convert this string to date type
How to get the date of the previous business day?
Getting Time Stamp in Date
How to convert "2022-04-11 18:55:00 CT" String Date format to "Mar 11 2022, 18:55 CST"
Forum Engagement Daily Reports
Hw to use file name from for each
String was not recognized as a valid DateTime error even after using DateTime.ParseExact
How to find difference between two date
Excel workbook
Write a time higher than the one obtained in string format
What is the filter expression for get exchange mails
Work days, Weekends and Controlling of Holidays?
Create variable from DateTime.Now
Input_DATE (-2)
How to check if string can be checked with DateTime.TryParse in Assing activity
Date Time format changed multiple times
String was not recognized as a valid DateTime like "45175"
Get difference for two dates in Months and Days
Could someone please provide step-by-step guidance on how to incorporate a DateTime activity into a UiPath sequence? I'm looking to create a process that involves handling date and time data, and I'm not sure where to start
Can use UiPath Click the calendar
If Condition: String was not recognized as a valid DateTime
Meaning of the error
How to get date 1sy day of month
Download email attachments from outlook, create folders in local directory
Could someone please provide step-by-step guidance on how to incorporate a DateTime activity into a UiPath sequence? I'm looking to create a process that involves handling date and time data, and I'm not sure where to start
Convert date to specific format
I Want to Covert the String Variable Contain "09222023" to this Format 22.09.2023
How to change the date formats
How to change the date formats
How to add dynamically todays date in Typeinto
Date comparison error _Panel
Alguien sabe como puedo capturar la hora exacta en Ui Path?
< DateTime Conversion>can anyone help with arstrStyles >> how to declare this variable?
Check if Extracted date is in specific format
"How to Convert Dates in Various Unknown Formats to dd.MM.yyyy in UiPath?"
Question about where to learn about DateTime
Question about where to learn about DateTime
Extract Date and Time from Text returning wrong output
Date Picker value to be stored in the variable
To get Current Date and Next Month date

Great Information!! @Palaniyappan

Thanks for this !!

1 Like

Great Job :clap: :clap:

Thanks for this valuable post @Palaniyappan

2 Likes

Very helpful buddy @Palaniyappan. thanks for sharing.

1 Like

Great @Palaniyappan , useful information to get all date format information Thank you.

1 Like

Thanks @Palaniyappan I have bookmarked for my own use and to share in the forums :blush:

This is a great post and I am sure it will be used frequently!

2 Likes

Thanks for the wonderful information @Palaniyappan

1 Like

wonderful post, thanks!!! :hugs:

2 Likes

This is great Post @Palaniyappan …it covers everything you need to know as developer. Saving hundred of hours by putting everything together.

1 Like

I am attempting to pull just the day of month from datetime. The “dd” option works but I wanted it without a leading zero so i used “d” which is an option according to microsoft. In UiPath using just “d” is giving me a full date instead of just the day.

Example
datetime = 04/01/2022
datetimeDate.ToString(“d”) giving “04/01/2022”
datetimeDate.ToString(“dd”) giving “01”

is there a different option in UiPath to get the day without leading zero?

@Palaniyappan Great information! Saved my day. Thanks a million

1 Like

Thank you so much to make community warriors life easy.

1 Like

Hi all,
I have a use case in which the ui element is selected based on the format “month.year”. I tried creating a string variable: Month_Year and save the current month and year using the syntax: datetime.Now.ToString(“MM.yyyy”). But when tried testing it by displaying the variable in a message box, nothing is being displayed.
image

Output :
image

Thanks in advance.

Regards
Midhun

I have Question Like, I tried this “now.ToString(“d-MM-yyyy”)” it gives output 3-2-2023. but question is will the Single d in dd-MM-yyyy will give all the dates in a month like? and single M will give the all Months like 1 to 12?

My colleague highlighted interesting bug: when using .ToString(“d”) it returns the whole date, not a day without leading zero. Let’s say the date in now variable is the 27th of April, 2023. So we expect "now.ToString(“d”) to return “27”, when it actually returns “04/27/2023”.

Bug is also mentioned here: I want to take date as 1 instead of 01 please help - #14 by keTan

The workaround proposed in that topic was to use .Day.ToString()
I’ve found out that you may also use .ToString(“%d”)

Actually, it’s not a bug, please check Custom date and time format strings | Microsoft Learn - https://learn.microsoft.com/:

A custom date and time format string consists of two or more characters. Date and time formatting methods interpret any single-character string as a standard date and time format string. If they don’t recognize the character as a valid format specifier, they throw a FormatException. For example, a format string that consists only of the specifier “h” is interpreted as a standard date and time format string. However, in this particular case, an exception is thrown because there is no “h” standard date and time format specifier.

“d” in your case is interpreted as “Short date pattern” (Standard date and time format strings | Microsoft Learn - https://learn.microsoft.com/).

2 Likes

Thank you @efelantti - I’ve acutally came back here to post a link to Custom date and time format strings | Microsoft Learn :slight_smile:

This is amazing thank you so much for this!!

str_firstdaylastmonth = New DateTime(now.Year,now.Month,1).AddMonths(-1).ToString

Simple, isn’t?
Cheers

Hello @Palaniyappan ,

Thanks for this detailed guide but somehow I am always getting error using any of these commands in the Assign activities to extract current month in "MM"and year “yyyy” format.
And DateTime.Now.ToString isn’t working at all.
only now.ToString is working for me.
Could this be a version issue?