6.2 DateTime Formatting, Timezone Conversions & TimeSpan Calculations
Key Takeaways
DateTime.ParseExact and TryParseExact with CultureInfo.InvariantCulture parse a known format the same way on every robot, whatever its regional settings.
Format specifiers are case-sensitive: MM is month and mm is minutes, HH is 24-hour and hh is 12-hour (pair it with tt), and fff is milliseconds.
Subtracting two DateTime values gives a TimeSpan; use TotalMinutes or TotalHours for thresholds, because Minutes and Hours return only one component.
Orchestrator stores timestamps in UTC and displays them in the configured time zone; each time trigger has its own time zone, and Add Queue Item accepts relative Deadline and Postpone expressions such as DateTime.Now.AddHours(2).
Business-day calculations loop day by day and skip weekends and a holiday list, often stored in an asset or data table.
6.2 DateTime Formatting, Timezone Conversions & TimeSpan Calculations
In enterprise automation workflows, temporal data drives critical business logic: calculating payment due dates, determining service-level agreement (SLA) deadlines, polling file directories for batch windows, and correlating transaction timestamps in Orchestrator logs. However, because unattended robots execute across geographically distributed virtual machines, cloud containers, and enterprise servers with differing regional locale settings, date and time handling is one of the most frequent causes of intermittent production failures.
To build robust, globally deployable automations, developers must master the System.DateTime, System.TimeSpan, and System.TimeZoneInfo types within the .NET runtime. This section provides an architectural deep dive into culture-invariant parsing, exact format masks, temporal arithmetic, duration benchmarking, UTC synchronization with Orchestrator, and business calendar algorithms.
1. Architectural Overview: System.DateTime & Culture-Dependent Parsing Pitfalls
In the .NET runtime, System.DateTime is an immutable value type representing a date and time as a 64-bit integer representing ticks (where 1 tick = 100 nanoseconds) elapsed since 12:00:00 AM on January 1, 0001 in the Gregorian calendar.
The Pitfall of DateTime.Parse() and Regional Settings
When developers use DateTime.Parse(dateString) or Convert.ToDateTime(dateString), the .NET runtime relies on CultureInfo.CurrentCulture—the regional settings of the Windows user account running the UiPath Robot service:
- On an American server (
en-US),"05/06/2026"parses as May 6, 2026. - On a British or Australian server (
en-GB), the exact same string parses as June 5, 2026. - On a system expecting
YYYY-MM-DD, passing"05/06/2026"throws an unhandledSystem.FormatException.
This introduces catastrophic data corruption in multi-tenant or cloud robot fleets, where a robot running in Frankfurt processes an invoice generated in New York and swaps the month and day.
Exact Parsing with DateTime.ParseExact
To enforce deterministic parsing regardless of robot OS culture, developers must use DateTime.ParseExact() with System.Globalization.CultureInfo.InvariantCulture:
' VB.NET: Deterministic parsing using CultureInfo.InvariantCulture
Dim rawDateStr As String = "2026-09-29 14:35:00"
Dim invoiceDate As DateTime = DateTime.ParseExact(rawDateStr, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture)
// C#: Deterministic parsing using CultureInfo.InvariantCulture
string rawDateStr = "2026-09-29 14:35:00";
DateTime invoiceDate = DateTime.ParseExact(rawDateStr, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
Defensive Non-Throwing Parsing with DateTime.TryParseExact
In unattended workflows processing external documents, dates may be malformed or blank. While DateTime.ParseExact throws a fatal FormatException on mismatched input, DateTime.TryParseExact returns a Boolean indicating success and outputs the parsed date via an Out argument without raising an exception:
' VB.NET: Defensive TryParseExact implementation in an Assign or If activity
Dim rawInput As String = "15/10/2026"
Dim parsedDate As DateTime
Dim isValidDate As Boolean = DateTime.TryParseExact(rawInput, _
"dd/MM/yyyy", _
System.Globalization.CultureInfo.InvariantCulture, _
System.Globalization.DateTimeStyles.None, _
parsedDate)
If isValidDate Then
' Proceed with valid date
Else
Throw New BusinessRuleException("The transaction date '" & rawInput & "' does not conform to the expected dd/MM/yyyy format.")
End If
Handling Multiple Acceptable Formats
When an upstream source formats dates inconsistently (e.g., legacy systems providing either yyyy-MM-dd or MM/dd/yyyy), pass an array of acceptable format strings:
' VB.NET: Parsing across multiple candidate date formats
Dim acceptableFormats As String() = {"yyyy-MM-dd", "MM/dd/yyyy", "dd/MM/yyyy", "yyyyMMdd"}
Dim success As Boolean = DateTime.TryParseExact(rawDateStr, _
acceptableFormats, _
System.Globalization.CultureInfo.InvariantCulture, _
System.Globalization.DateTimeStyles.None, _
parsedDate)
2. Comprehensive Custom & Standard DateTime Format Specifiers
When parsing strings into DateTime objects or formatting DateTime instances for presentation, specifiers are strictly case-sensitive. Confusing letter casing is a primary trap on professional certification exams.
| Specifier | Definition | Example (2026-09-08 07:05:09.045) | Common Pitfall / Architectural Note |
|---|---|---|---|
yyyy | 4-digit year | "2026" | Use yyyy instead of yy to prevent 20th vs 21st century ambiguity. |
yy | 2-digit year | "26" | Truncates century; prone to century rollover misinterpretation. |
MM | 2-digit month (01–12) | "09" | UPPERCASE MM. Lowercase mm is minutes! |
M | 1 or 2-digit month (1–12) | "9" | No leading zero for single-digit months. |
MMM | Abbreviated month name | "Sep" | Culture-dependent unless InvariantCulture is specified. |
MMMM | Full month name | "September" | Culture-dependent unless InvariantCulture is specified. |
dd | 2-digit day of month (01–31) | "08" | Zero-padded day of month. |
d | 1 or 2-digit day of month (1–31) | "8" | Unpadded day of month. |
ddd | Abbreviated day of week | "Tue" | e.g., Mon, Tue, Wed. |
dddd | Full day of week | "Tuesday" | e.g., Monday, Tuesday. |
HH | 24-hour hour (00–23) | "07" (or "19" for 7 PM) | UPPERCASE HH. Standard military/enterprise time. |
hh | 12-hour hour (01–12) | "07" | LOWERCASE hh. Must be paired with tt (AM/PM) to distinguish morning from evening! |
mm | Minutes (00–59) | "05" | LOWERCASE mm. Uppercase MM is month! |
ss | Seconds (00–59) | "09" | Zero-padded seconds. |
fff | Milliseconds (3 digits) | "045" | Fractional seconds to 3 decimal places. |
tt | AM/PM designator | "AM" (or "PM") | Required when using 12-hour format (hh). |
K | Timezone representation | "-04:00", "Z", or empty | Serializes timezone information for ISO 8601 strings. |
' Formatting example: Generating an ISO 8601 timestamp for a REST API payload
Dim isoTimestamp As String = DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'")
' Output: "2026-09-29T14:35:00.045Z"
3. Date Arithmetic & Manipulation Methods
DateTime objects are immutable. Calling an arithmetic method does not alter the original variable; it returns a new DateTime instance.
Core Arithmetic Methods
.AddDays(Double): Adds or subtracts days. Negative values subtract days (e.g.,now.AddDays(-7)for one week ago). Fractional values represent partial days (e.g.,0.5adds 12 hours)..AddMonths(Int32): Adds months, intelligently adjusting for varying month lengths (e.g., adding 1 month to January 31 yields February 28 or 29)..AddYears(Int32): Adds years, handling leap year adjustments..AddHours(Double),.AddMinutes(Double),.AddSeconds(Double): Adjusts specific time increments.
Calculating Fiscal and Month Boundaries
Common reporting automations require calculating the first or last day of a period:
' VB.NET: First day of current month
Dim firstDayCurrentMonth As New DateTime(DateTime.Now.Year, DateTime.Now.Month, 1)
' VB.NET: Last day of current month (First day of next month minus one day)
Dim lastDayCurrentMonth As DateTime = (New DateTime(DateTime.Now.Year, DateTime.Now.Month, 1)).AddMonths(1).AddDays(-1)
' VB.NET: First day of previous month
Dim firstDayPrevMonth As DateTime = (New DateTime(DateTime.Now.Year, DateTime.Now.Month, 1)).AddMonths(-1)
4. System.TimeSpan Durations, Benchmarking & Timeouts
While DateTime represents a discrete moment on the timeline, System.TimeSpan represents an elapsed duration or time interval.
Instantiating TimeSpan
Developers instantiate TimeSpan objects using static factory methods:
TimeSpan.FromDays(2.5)TimeSpan.FromHours(1.5)TimeSpan.FromMinutes(30)TimeSpan.FromSeconds(45)TimeSpan.FromMilliseconds(500)
Calculating Duration Between Two Dates
Subtracting one DateTime from another yields a TimeSpan:
' VB.NET: Measuring transaction execution duration
Dim startTime As DateTime = DateTime.Now
' ... Execute transactional business logic ...
Dim endTime As DateTime = DateTime.Now
Dim executionTime As TimeSpan = endTime.Subtract(startTime)
' Or: Dim executionTime As TimeSpan = endTime - startTime
The Critical Architectural Trap: Total Properties vs. Component Properties
Understanding the distinction between unit component properties and total cumulative properties is vital for SLA logic:
| Property | Return Type | Definition & Architectural Behavior |
|---|---|---|
Hours | Int32 | Represents only the hour component (0 to 23) of the interval. For an interval of 26 hours, Hours returns 2! |
TotalHours | Double | Represents the entire elapsed duration expressed in hours, including fractional parts. For 26 hours and 30 minutes, returns 26.5. |
Minutes | Int32 | Represents only the minute component (-59 to 59). For an interval of 75 minutes, returns 15. |
TotalMinutes | Double | Represents the complete elapsed duration expressed in minutes. For 75 minutes, returns 75.0. |
Seconds | Int32 | Component seconds (0 to 59). |
TotalSeconds | Double | Total elapsed duration in seconds. For 2 minutes and 15 seconds, returns 135.0. |
Caution
If checking whether a transaction exceeded an SLA of 60 minutes, evaluating executionDuration.Minutes > 60 will never evaluate to True because Minutes caps at 59! Always evaluate executionDuration.TotalMinutes > 60.0.
5. Time Zones: Orchestrator, Triggers & Robots
Robots, Orchestrator, and users may all be in different time zones, so it matters which clock a value refers to:
- Orchestrator storage and display. Orchestrator stores timestamps such as job start times and queue item creation times in UTC, and shows them in the time zone configured for the tenant or user.
- Time triggers. Each time trigger has its own Timezone setting, so a trigger set to 08:00 Eastern Time runs at 08:00 Eastern regardless of where the robot sits.
- Queue item dates. On Add Queue Item, the Deadline and Postpone properties accept relative expressions. Orchestrator's queue documentation gives examples such as
DateTime.Now.AddHours(2)andDateTime.Now.AddDays(10), and also accepts an exact US-format date such as10/15/2019 07:40:00. On the retrievedQueueItemobject, the same values appear asDueDateandDeferDate. - Robot machines.
DateTime.Nowuses the robot machine's local time zone. If Dispatcher and Performer robots run in different regions, agree on one convention, such as storing UTC inSpecificContentand converting only for display.
The risky values are strings and dates of kind Unspecified, for example a date parsed from a spreadsheet with no zone information. Convert them explicitly with TimeZoneInfo before comparing them with DateTime.Now or DateTime.UtcNow.
Converting Between UTC and Local Time
The System.TimeZoneInfo class manages timezone conversions and automatically accounts for Daylight Saving Time (DST) transitions.
' VB.NET: Converting a local business deadline to UTC before storing it in SpecificContent
Dim localDeadline As DateTime = DateTime.Now.AddHours(4)
Dim utcDeadline As DateTime = TimeZoneInfo.ConvertTimeToUtc(localDeadline)
' Store the value in the item data, for example ItemInformation("DeadlineUtc") = utcDeadline
' VB.NET: Converting UTC Queue Item Creation Time to Specific Regional Timezone
' Useful for customer-facing notification emails
Dim queueItemUtc As DateTime = transactionItem.SpecificContent("CreatedAtUtc")
Dim easternZone As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")
Dim localEasternTime As DateTime = TimeZoneInfo.ConvertTimeFromUtc(queueItemUtc, easternZone)
Console.WriteLine("Transaction initiated at Eastern Time: " & localEasternTime.ToString("yyyy-MM-dd HH:mm:ss"))
// C#: TimeZone conversion by system timezone ID
DateTime utcTime = DateTime.UtcNow;
DateTime tokyoTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcTime, "UTC", "Tokyo Standard Time");
6. Business Day & Holiday Calculation Architecture
Enterprise automations frequently require scheduling transactions based on business days (e.g., "process invoice on the 3rd business day following receipt" or "set queue item deadline 48 business hours out, excluding weekends and national holidays").
The Business Day Algorithm
A resilient business day calculation requires:
- Identifying weekend days using
dateTime.DayOfWeek(DayOfWeek.SaturdayorDayOfWeek.Sunday). - Maintaining an audited collection of bank/corporate holidays (stored in an Orchestrator Asset, database table, or JSON configuration).
- Utilizing a
HashSet(Of DateTime)for high-performanceO(1)holiday membership lookups. - Incrementing or decrementing in a procedural while-loop until the target number of business days is reached.
' VB.NET: Add N Business Days excluding weekends and corporate holidays
Dim currentDate As DateTime = DateTime.Today
Dim businessDaysToAdd As Integer = 5
Dim holidays As New HashSet(Of DateTime) From {
New DateTime(2026, 1, 1), ' New Year's Day
New DateTime(2026, 7, 4), ' Independence Day
New DateTime(2026, 12, 25) ' Christmas Day
}
Dim addedDays As Integer = 0
While addedDays < businessDaysToAdd
currentDate = currentDate.AddDays(1)
' Check if current date is Saturday, Sunday, or Holiday
Dim isWeekend As Boolean = (currentDate.DayOfWeek = DayOfWeek.Saturday OrElse currentDate.DayOfWeek = DayOfWeek.Sunday)
Dim isHoliday As Boolean = holidays.Contains(currentDate.Date)
If Not isWeekend AndAlso Not isHoliday Then
addedDays += 1
End If
End While
Dim targetDueDate As DateTime = currentDate
' targetDueDate is now guaranteed to be 5 business days in the future
// C#: Add N Business Days
DateTime currentDate = DateTime.Today;
int businessDaysToAdd = 5;
HashSet<DateTime> holidays = new HashSet<DateTime> {
new DateTime(2026, 1, 1),
new DateTime(2026, 7, 4),
new DateTime(2026, 12, 25)
};
int addedDays = 0;
while (addedDays < businessDaysToAdd) {
currentDate = currentDate.AddDays(1);
bool isWeekend = currentDate.DayOfWeek == DayOfWeek.Saturday || currentDate.DayOfWeek == DayOfWeek.Sunday;
bool isHoliday = holidays.Contains(currentDate.Date);
if (!isWeekend && !isHoliday) {
addedDays++;
}
}
An unattended robot executing on a Windows virtual machine configured with UK regional settings (en-GB) parses an invoice string "04/05/2026" representing April 5, 2026. The developer uses DateTime.Parse(rawDate). What failure occurs, and what is the proper architectural remedy?
A FormatException is thrown immediately; the developer should replace the string slashes with hyphens
The code compiles but throws an OverflowException; the developer should cast the string to a Double
The string is parsed as May 4, 2026 due to regional dd/MM/yyyy interpretation; the developer must use DateTime.ParseExact with "MM/dd/yyyy" and CultureInfo.InvariantCulture
The robot succeeds without issue because UiPath Studio automatically forces en-US formatting across all unattended executions
A developer needs to determine if an automated database reconciliation task took longer than 90 minutes to execute. The duration is captured in a TimeSpan variable named executionDuration. Which expression correctly evaluates this condition?
executionDuration.Minutes > 90
executionDuration.TotalMinutes > 90.0
executionDuration.Hours >= 1 AndAlso executionDuration.Minutes > 30
TimeSpan.FromMinutes(executionDuration.Minutes) > 90
A Dispatcher must give each new queue item a deadline four hours after it is added. According to Orchestrator's queue documentation, which Add Queue Item configuration does this?
Deadline = DateTime.Now.AddHours(4)
Postpone = DateTime.Now.AddHours(4)
Deadline = DateTime.Today.AddHours(4)
Priority = High with a queue SLA of four days
Sections you finish are checked off in the contents.