diff --git a/docs/core/install/linux-snap-runtime.md b/docs/core/install/linux-snap-runtime.md index a012e1f280a56..c6e98f82ff6b5 100644 --- a/docs/core/install/linux-snap-runtime.md +++ b/docs/core/install/linux-snap-runtime.md @@ -3,7 +3,7 @@ title: Install .NET Runtime on Linux with Snap description: Learn about how to install the .NET Runtime snap package. Canonical maintains and supports .NET-related snap packages. author: adegeo ms.author: adegeo -ms.date: 12/13/2024 +ms.date: 01/16/2026 ms.topic: install-set-up-deploy ms.custom: linux-related-content #customer intent: As a Linux user, I want to install .NET Runtime through Snap. diff --git a/docs/core/install/macos-notarization-issues.md b/docs/core/install/macos-notarization-issues.md index 0ab0881543138..a9e247233ab03 100644 --- a/docs/core/install/macos-notarization-issues.md +++ b/docs/core/install/macos-notarization-issues.md @@ -3,7 +3,7 @@ title: Working with macOS Catalina Notarization description: How to handle notarization and certificate problems with macOS when you install the .NET runtime, SDK, and apps built with .NET. author: adegeo ms.author: adegeo -ms.date: 11/11/2024 +ms.date: 01/16/2026 --- # macOS Catalina Notarization and the impact on .NET downloads and projects diff --git a/docs/standard/base-types/parsing-datetime.md b/docs/standard/base-types/parsing-datetime.md index f952034fc02a9..d05320ebe95de 100644 --- a/docs/standard/base-types/parsing-datetime.md +++ b/docs/standard/base-types/parsing-datetime.md @@ -1,8 +1,9 @@ --- -title: Convert strings to DateTime -description: "Learn techniques to parse strings that represent dates and times to create a DateTime from the date and time string." -ms.date: 07/08/2022 +title: Parse date and time strings +description: "Learn techniques to parse strings that represent dates and times to create DateTime, DateOnly, and TimeOnly objects from string representations." +ms.date: 01/16/2026 ms.custom: devdivchpfy22 +ai-usage: ai-assisted dev_langs: - "csharp" - "vb" @@ -13,21 +14,48 @@ helpviewer_keywords: - "enumerations [.NET], parsing strings" - "base types, parsing strings" - "DateTime object" + - "DateOnly structure" + - "TimeOnly structure" - "time strings" --- # Parse date and time strings in .NET -Parsing strings to convert them to objects requires you to specify information about how the dates and times are represented as text. Different cultures use different orders for day, month, and year. Some time representations use a 24-hour clock, others specify "AM" and "PM." Some applications need only the date. Others need only the time. Still others need to specify both the date and time. The methods that convert strings to objects enable you to provide detailed information about the formats you expect and the elements of a date and time your application needs. There are three subtasks to correctly converting text into a : +.NET provides several types for working with date and time data, each optimized for different scenarios: -1. You must specify the expected format of the text representing a date and time. -1. You can specify the culture for the format of a date time. -1. You can specify how missing components in the text representation are set in the date and time. +- **** - Represents a date and time together, ideal when you need both components or when working with legacy code. +- **** (not available in .NET Framework) - Represents only a date without time information, perfect for birthdays, anniversaries, or business dates. +- **** (not available in .NET Framework) - Represents only a time without date information, ideal for schedules, alarms, or recurring daily events. -The and methods convert many common representations of a date and time. The and methods convert a string representation that conforms to the pattern specified by a date and time format string. For more information, see the articles on [standard date and time format strings](standard-date-and-time-format-strings.md) and [custom date and time format strings](custom-date-and-time-format-strings.md). +Each type provides parsing methods that convert strings to their respective objects, with different levels of flexibility and control over the parsing process. -The current object provides more control over how text should be interpreted as a date and time. Properties of a describe the date and time separators, the names of months, days, and eras, and the format for the "AM" and "PM" designations. The returned by has a property that represents the current culture. If you want a specific culture or custom settings, you specify the parameter of a parsing method. For the parameter, specify a object, which represents a culture, or a object. +## Common parsing concepts -The text representing a date or time might be missing some information. For example, most people would assume the date "March 12" represents the current year. Similarly, "March 2018" represents the month of March in the year 2018. Text representing time often does only include hours, minutes, and an AM/PM designation. Parsing methods handle this missing information by using reasonable defaults: +All three date and time types share similar parsing approaches: + +- **`Parse` and `TryParse` methods** - Convert many common string representations using current culture or specified culture settings. +- **`ParseExact` and `TryParseExact` methods** - Convert strings that conform to specific format patterns, providing precise control over expected formats, including culture settings. +- **Format strings** - Define patterns for parsing using standard or custom format specifiers. + +Different cultures use different orders for day, month, and year. Some time representations use a 24-hour clock, others specify "AM" and "PM." The parsing methods handle these variations through culture-specific formatting rules. + +The object provides control over how text should be interpreted. Properties describe the date and time separators, names of months, days, eras, and the format for "AM" and "PM" designations. You can specify culture through the parameter using a object or a object. + +For more information about format patterns, see [standard date and time format strings](standard-date-and-time-format-strings.md) and [custom date and time format strings](custom-date-and-time-format-strings.md). + +> [!IMPORTANT] +> and types aren't available for .NET Framework. + +## DateTime parsing + + represents both date and time components together. When parsing strings to `DateTime` objects, you need to consider several `DateTime`-specific aspects: + +- **Missing information handling** - `DateTime` uses defaults when parts are missing from the input string. +- **Time zone and UTC offset support** - `DateTime` can represent local, UTC, or unspecified time zones. +- **Combined date and time parsing** - Must handle both date and time components in a single operation. + +### Missing information handling + +The text representing a date or time might be missing some information. For example, most people would assume the date "March 12" represents the current year. Similarly, "March 2018" represents the month of March in the year 2018. Text representing time often includes only hours, minutes, and an AM/PM designation. `DateTime` parsing methods handle this missing information by using reasonable defaults: - When only the time is present, the date portion uses the current date. - When only the date is present, the time portion is midnight. @@ -38,42 +66,93 @@ If the date is present in the string, it must include the month and one of the d You can specify the constant to override these defaults. When you use that constant, any missing year, month, or day properties are set to the value `1`. The [last example](#styles-example) using demonstrates this behavior. -In addition to a date and a time component, the string representation of a date and time can include an offset that indicates how much the time differs from Coordinated Universal Time (UTC). For example, the string "2/14/2007 5:32:00 -7:00" defines a time that is seven hours earlier than UTC. If an offset is omitted from the string representation of a time, parsing returns a object with its property set to . If an offset is specified, parsing returns a object with its property set to . Its value is also adjusted to the local time zone of your machine. You can modify this behavior by using a value with the parsing method. +### UTC offset and time zone handling -The format provider is also used to interpret an ambiguous numeric date. It's unclear which components of the date represented by the string "02/03/04" are the month, day, and year. The components are interpreted according to the order of similar date formats in the format provider. +In addition to a date and a time component, the string representation of a date and time can include an offset that indicates how much the time differs from Coordinated Universal Time (UTC). For example, the string "2/14/2007 5:32:00 -7:00" defines a time that's seven hours earlier than UTC. If an offset is omitted from the string representation of a time, parsing returns a object with its property set to . If an offset is specified, parsing returns a object with its property set to . Its value is also adjusted to the local time zone of your machine. You can modify this behavior by using a value with the parsing method. -## Parse +### Ambiguous date handling + +The format provider is also used to interpret an ambiguous numeric date. It's unclear which components of the date represented by the string "02/03/04" are the month, day, and year. The components are interpreted according to the order of similar date formats in the format provider. -The following example illustrates the use of the method to convert a `string` into a . This example uses the culture associated with the current thread. If the associated with the current culture can't parse the input string, a is thrown. +### DateTime.Parse -> [!NOTE] -> These examples are available in the GitHub docs repo for both [C#](https://github.com/dotnet/docs/tree/main/samples/snippets/csharp/how-to/conversions) and [Visual Basic](https://github.com/dotnet/docs/tree/main/samples/snippets/visualbasic/how-to/conversions). +The following example shows the use of the method to convert a `string` into a . This example uses the culture associated with the current thread. If the associated with the current culture can't parse the input string, a is thrown. -[!code-csharp[Parsing.DateAndTime#1](../../../samples/snippets/csharp/how-to/conversions/StringToDateTime.cs#1)] -[!code-vb[Parsing.DateAndTime#1](../../../samples/snippets/visualbasic/how-to/conversions/Program.vb#1)] +:::code source="./snippets/parsing-datetime/csharp/Program.cs" id="DateTimeParse" language="csharp"::: +:::code source="./snippets/parsing-datetime/vb/Program.vb" id="DateTimeParse" language="vb"::: You can also explicitly define the culture whose formatting conventions are used when you parse a string. You specify one of the standard objects returned by the property. The following example uses a format provider to parse a German string into a . It creates a representing the `de-DE` culture. That `CultureInfo` object ensures successful parsing of this particular string. This process precludes whatever setting is in the of the . -[!code-csharp[Parsing.DateAndTime#2](../../../samples/snippets/csharp/how-to/conversions/StringToDateTime.cs#2)] -[!code-vb[Parsing.DateAndTime#2](../../../samples/snippets/visualbasic/how-to/conversions/Program.vb#2)] +:::code language="csharp" source="./snippets/parsing-datetime/csharp/Program.cs" id="DateTimeParseCulture"::: +:::code source="./snippets/parsing-datetime/vb/Program.vb" id="DateTimeParseCulture" language="vb"::: However, you can use overloads of the method to specify custom format providers. The method doesn't support parsing non-standard formats. To parse a date and time expressed in a non-standard format, use the method instead. The following example uses the enumeration to specify that the current date and time information shouldn't be added to the for unspecified fields. -[!code-csharp[Parsing.DateAndTime#3](../../../samples/snippets/csharp/how-to/conversions/StringToDateTime.cs#3)] -[!code-vb[Parsing.DateAndTime#3](../../../samples/snippets/visualbasic/how-to/conversions/Program.vb#3)] +:::code source="./snippets/parsing-datetime/csharp/Program.cs" id="DateTimeParseNoDefault" language="csharp"::: +:::code source="./snippets/parsing-datetime/vb/Program.vb" id="DateTimeParseNoDefault" language="vb"::: -## ParseExact +### DateTime.ParseExact The method converts a string to a object if it conforms to one of the specified string patterns. When a string that isn't one of the forms specified is passed to this method, a is thrown. You can specify one of the standard date and time format specifiers or a combination of the custom format specifiers. Using the custom format specifiers, it's possible for you to construct a custom recognition string. For an explanation of the specifiers, see the articles on [standard date and time format strings](standard-date-and-time-format-strings.md) and [custom date and time format strings](custom-date-and-time-format-strings.md). In the following example, the method is passed a string object to parse, followed by a format specifier, followed by a object. This method can only parse strings that follow the long date pattern in the `en-US` culture. -[!code-csharp[Parsing.DateAndTime#4](../../../samples/snippets/csharp/how-to/conversions/StringToDateTime.cs#4)] -[!code-vb[Parsing.DateAndTime#4](../../../samples/snippets/visualbasic/how-to/conversions/Program.vb#4)] +:::code source="./snippets/parsing-datetime/csharp/Program.cs" id="DateTimeParseExact" language="csharp"::: +:::code source="./snippets/parsing-datetime/vb/Program.vb" id="DateTimeParseExact" language="vb"::: + +Each overload of the and methods also has an parameter that provides culture-specific information about the formatting of the string. The object is a object that represents a standard culture or a object that's returned by the property. also uses an additional string or string array argument that defines one or more custom date and time formats. + +## DateOnly parsing + +The structure represents only a date without time information, making it perfect for scenarios like birthdays, anniversaries, or business dates. Since it has no time component, it represents a date from the start of the day to the end of the day. + +`DateOnly` has several advantages over using `DateTime` for date-only scenarios: + +- The `DateTime` structure might roll into the previous or next day if it's offset by a time zone. `DateOnly` can't be offset by a time zone, and it always represents the date that was set. +- Serializing a `DateOnly` includes less data than `DateTime`. +- When code interacts with a database, such as SQL Server, whole dates are generally stored as the `date` data type, which doesn't include a time. `DateOnly` matches the database type better. + +### DateOnly.Parse + +The method converts common date string representations to a object. The method accepts various formats and uses the current culture or a specified culture for parsing. + +:::code source="./snippets/parsing-datetime/csharp/Program.cs" id="DateOnlyParse" language="csharp"::: +:::code source="./snippets/parsing-datetime/vb/Program.vb" id="DateOnlyParse" language="vb"::: + +### DateOnly.ParseExact + +The method provides precise control over the expected format of the input string. Use this method when you know the exact format of the date string and want to ensure strict parsing. + +:::code source="./snippets/parsing-datetime/csharp/Program.cs" id="DateOnlyParseExact" language="csharp"::: +:::code source="./snippets/parsing-datetime/vb/Program.vb" id="DateOnlyParseExact" language="vb"::: + +The `ParseExact` method accepts either a single format string or an array of format strings, allowing you to parse dates that might come in multiple acceptable formats. + +## TimeOnly parsing + +The structure represents a time-of-day value, such as a daily alarm clock or what time you eat lunch each day. `TimeOnly` is limited to the range of **00:00:00.0000000** - **23:59:59.9999999**, a specific time of day. + +`TimeOnly` solves several problems that existed when using other types for time-only scenarios: + +- `TimeSpan` represents elapsed time and can be negative or exceed 24 hours, making it unsuitable for representing a specific time of day. +- Using `DateTime` for a time of day requires an arbitrary date, which can lead to unexpected behavior when performing calculations. +- `TimeOnly` naturally handles 24-hour rollover when adding or subtracting time values. + +### TimeOnly.Parse + +The method converts common time string representations to a object. The method accepts various formats including 12-hour and 24-hour notation. + +:::code source="./snippets/parsing-datetime/csharp/Program.cs" id="TimeOnlyParse" language="csharp"::: +:::code source="./snippets/parsing-datetime/vb/Program.vb" id="TimeOnlyParse" language="vb"::: + +### TimeOnly.ParseExact + +The method provides precise control over the expected format of the input time string. Use this method when you know the exact format and want to ensure strict parsing. -Each overload of the and methods also has an parameter that provides culture-specific information about the formatting of the string. The object is a object that represents a standard culture or a object that is returned by the property. also uses an additional string or string array argument that defines one or more custom date and time formats. +:::code source="./snippets/parsing-datetime/csharp/Program.cs" id="TimeOnlyParseExact" language="csharp"::: +:::code source="./snippets/parsing-datetime/vb/Program.vb" id="TimeOnlyParseExact" language="vb"::: ## See also @@ -82,3 +161,4 @@ Each overload of the and + static void DateTimeParseExample() + { + // Parse common date and time formats using current culture + var dateTime1 = DateTime.Parse("1/15/2025 3:30 PM"); + var dateTime2 = DateTime.Parse("January 15, 2025"); + var dateTime3 = DateTime.Parse("15:30:45"); + + Console.WriteLine($"Parsed: {dateTime1}"); + Console.WriteLine($"Parsed: {dateTime2}"); + Console.WriteLine($"Parsed: {dateTime3}"); + + // Parse with specific culture + var germanDate = DateTime.Parse("15.01.2025", new CultureInfo("de-DE")); + Console.WriteLine($"German date parsed: {germanDate}"); + } + // + + // + static void DateTimeParseExactExample() + { + // Parse exact format + var exactDate = DateTime.ParseExact("2025-01-15T14:30:00", "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture); + Console.WriteLine($"Exact parse: {exactDate}"); + + // Parse with custom format + var customDate = DateTime.ParseExact("15/Jan/2025 2:30 PM", "dd/MMM/yyyy h:mm tt", CultureInfo.InvariantCulture); + Console.WriteLine($"Custom format: {customDate}"); + } + // + + // + static void DateTimeParseGermanExample() + { + var cultureInfo = new CultureInfo("de-DE"); + string dateString = "12 Juni 2008"; + var dateTime = DateTime.Parse(dateString, cultureInfo); + Console.WriteLine(dateTime); + // The example displays the following output: + // 6/12/2008 00:00:00 + } + // + + // + static void DateTimeParseNoDefaultExample() + { + var cultureInfo = new CultureInfo("de-DE"); + string dateString = "12 Juni 2008"; + var dateTime = DateTime.Parse(dateString, cultureInfo, + DateTimeStyles.NoCurrentDateDefault); + Console.WriteLine(dateTime); + // The example displays the following output if the current culture is en-US: + // 6/12/2008 00:00:00 + } + // + + // + static void DateOnlyParseExample() + { + // Parse common date formats + var date1 = DateOnly.Parse("1/15/2025"); + var date2 = DateOnly.Parse("January 15, 2025", CultureInfo.InvariantCulture); + var date3 = DateOnly.Parse("2025-01-15"); + + Console.WriteLine($"Parsed date: {date1}"); + Console.WriteLine($"Parsed date: {date2.ToString("D")}"); // Long date format + Console.WriteLine($"Parsed date: {date3.ToString("yyyy-MM-dd")}"); + + // Parse with specific culture + var germanDate = DateOnly.Parse("15.01.2025", new CultureInfo("de-DE")); + Console.WriteLine($"German date: {germanDate}"); + } + // + + // + static void DateOnlyParseExactExample() + { + // Parse exact format + var exactDate = DateOnly.ParseExact("21 Oct 2015", "dd MMM yyyy", CultureInfo.InvariantCulture); + Console.WriteLine($"Exact date: {exactDate}"); + + // Parse ISO format + var isoDate = DateOnly.ParseExact("2025-01-15", "yyyy-MM-dd", CultureInfo.InvariantCulture); + Console.WriteLine($"ISO date: {isoDate}"); + + // Parse with multiple possible formats + string[] formats = { "MM/dd/yyyy", "M/d/yyyy", "dd/MM/yyyy" }; + var flexibleDate = DateOnly.ParseExact("1/15/2025", formats, CultureInfo.InvariantCulture, DateTimeStyles.None); + Console.WriteLine($"Flexible parse: {flexibleDate}"); + } + // + + // + static void TimeOnlyParseExample() + { + // Parse common time formats + var time1 = TimeOnly.Parse("14:30:15"); + var time2 = TimeOnly.Parse("2:30 PM", CultureInfo.InvariantCulture); + var time3 = TimeOnly.Parse("17:45"); + + Console.WriteLine($"Parsed time: {time1}"); + Console.WriteLine($"Parsed time: {time2.ToString("t")}"); // Short time format + Console.WriteLine($"Parsed time: {time3.ToString("HH:mm")}"); + + // Parse with milliseconds + var preciseTime = TimeOnly.Parse("14:30:15.123"); + Console.WriteLine($"Precise time: {preciseTime.ToString("HH:mm:ss.fff")}"); + } + // + + // + static void TimeOnlyParseExactExample() + { + // Parse exact format + var exactTime = TimeOnly.ParseExact("5:00 pm", "h:mm tt", CultureInfo.InvariantCulture); + Console.WriteLine($"Exact time: {exactTime}"); + + // Parse 24-hour format + var militaryTime = TimeOnly.ParseExact("17:30:25", "HH:mm:ss", CultureInfo.InvariantCulture); + Console.WriteLine($"Military time: {militaryTime}"); + + // Parse with multiple possible formats + string[] timeFormats = { "h:mm tt", "HH:mm", "H:mm" }; + var flexibleTime = TimeOnly.ParseExact("2:30 PM", timeFormats, CultureInfo.InvariantCulture, DateTimeStyles.None); + Console.WriteLine($"Flexible time parse: {flexibleTime}"); + } + // + } +} \ No newline at end of file diff --git a/samples/snippets/csharp/how-to/conversions/conversions.csproj b/docs/standard/base-types/snippets/parsing-datetime/csharp/parsing-datetime.csproj similarity index 70% rename from samples/snippets/csharp/how-to/conversions/conversions.csproj rename to docs/standard/base-types/snippets/parsing-datetime/csharp/parsing-datetime.csproj index af31fefa23aa5..a5bdb8bb0cc69 100644 --- a/samples/snippets/csharp/how-to/conversions/conversions.csproj +++ b/docs/standard/base-types/snippets/parsing-datetime/csharp/parsing-datetime.csproj @@ -2,8 +2,8 @@ Exe - net8.0 + net10.0 enable - + \ No newline at end of file diff --git a/docs/standard/base-types/snippets/parsing-datetime/vb/Program.vb b/docs/standard/base-types/snippets/parsing-datetime/vb/Program.vb new file mode 100644 index 0000000000000..436d4a9521d3a --- /dev/null +++ b/docs/standard/base-types/snippets/parsing-datetime/vb/Program.vb @@ -0,0 +1,139 @@ +Imports System.Globalization + +Module Program + Sub Main(args As String()) + Console.WriteLine("=== DateTime Parsing Examples ===") + DateTimeParseExample() + DateTimeParseGermanExample() + DateTimeParseNoDefaultExample() + DateTimeParseExactExample() + + Console.WriteLine(Environment.NewLine & "=== DateOnly Parsing Examples ===") + DateOnlyParseExample() + DateOnlyParseExactExample() + + Console.WriteLine(Environment.NewLine & "=== TimeOnly Parsing Examples ===") + TimeOnlyParseExample() + TimeOnlyParseExactExample() + End Sub + + ' + Sub DateTimeParseExample() + ' Parse common date and time formats using current culture + Dim dateTime1 = DateTime.Parse("1/15/2025 3:30 PM") + Dim dateTime2 = DateTime.Parse("January 15, 2025") + Dim dateTime3 = DateTime.Parse("15:30:45") + + Console.WriteLine($"Parsed: {dateTime1}") + Console.WriteLine($"Parsed: {dateTime2}") + Console.WriteLine($"Parsed: {dateTime3}") + + ' Parse with specific culture + Dim germanDate = DateTime.Parse("15.01.2025", New CultureInfo("de-DE")) + Console.WriteLine($"German date parsed: {germanDate}") + End Sub + ' + + ' + Sub DateTimeParseExactExample() + ' Parse exact format + Dim exactDate = DateTime.ParseExact("2025-01-15T14:30:00", "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture) + Console.WriteLine($"Exact parse: {exactDate}") + + ' Parse with custom format + Dim customDate = DateTime.ParseExact("15/Jan/2025 2:30 PM", "dd/MMM/yyyy h:mm tt", CultureInfo.InvariantCulture) + Console.WriteLine($"Custom format: {customDate}") + End Sub + ' + + ' + Sub DateTimeParseGermanExample() + Dim MyCultureInfo As New CultureInfo("de-DE") + Dim MyString As String = "12 Juni 2008" + Dim MyDateTime As DateTime = DateTime.Parse(MyString, MyCultureInfo) + Console.WriteLine(MyDateTime) + ' The example displays the following output: + ' 6/12/2008 00:00:00 + End Sub + ' + + ' + Sub DateTimeParseNoDefaultExample() + Dim MyCultureInfo As New CultureInfo("de-DE") + Dim MyString As String = "12 Juni 2008" + Dim MyDateTime As DateTime = DateTime.Parse(MyString, MyCultureInfo, + DateTimeStyles.NoCurrentDateDefault) + Console.WriteLine(MyDateTime) + ' The example displays the following output if the current culture is en-US: + ' 6/12/2008 00:00:00 + End Sub + ' + + ' + Sub DateOnlyParseExample() + ' Parse common date formats + Dim date1 = DateOnly.Parse("1/15/2025") + Dim date2 = DateOnly.Parse("January 15, 2025", CultureInfo.InvariantCulture) + Dim date3 = DateOnly.Parse("2025-01-15") + + Console.WriteLine($"Parsed date: {date1}") + Console.WriteLine($"Parsed date: {date2.ToString("D")}") ' Long date format + Console.WriteLine($"Parsed date: {date3.ToString("yyyy-MM-dd")}") + + ' Parse with specific culture + Dim germanDate = DateOnly.Parse("15.01.2025", New CultureInfo("de-DE")) + Console.WriteLine($"German date: {germanDate}") + End Sub + ' + + ' + Sub DateOnlyParseExactExample() + ' Parse exact format + Dim exactDate = DateOnly.ParseExact("21 Oct 2015", "dd MMM yyyy", CultureInfo.InvariantCulture) + Console.WriteLine($"Exact date: {exactDate}") + + ' Parse ISO format + Dim isoDate = DateOnly.ParseExact("2025-01-15", "yyyy-MM-dd", CultureInfo.InvariantCulture) + Console.WriteLine($"ISO date: {isoDate}") + + ' Parse with multiple possible formats + Dim formats() As String = {"MM/dd/yyyy", "M/d/yyyy", "dd/MM/yyyy"} + Dim flexibleDate = DateOnly.ParseExact("1/15/2025", formats, CultureInfo.InvariantCulture, DateTimeStyles.None) + Console.WriteLine($"Flexible parse: {flexibleDate}") + End Sub + ' + + ' + Sub TimeOnlyParseExample() + ' Parse common time formats + Dim time1 = TimeOnly.Parse("14:30:15") + Dim time2 = TimeOnly.Parse("2:30 PM", CultureInfo.InvariantCulture) + Dim time3 = TimeOnly.Parse("17:45") + + Console.WriteLine($"Parsed time: {time1}") + Console.WriteLine($"Parsed time: {time2.ToString("t")}") ' Short time format + Console.WriteLine($"Parsed time: {time3.ToString("HH:mm")}") + + ' Parse with milliseconds + Dim preciseTime = TimeOnly.Parse("14:30:15.123") + Console.WriteLine($"Precise time: {preciseTime.ToString("HH:mm:ss.fff")}") + End Sub + ' + + ' + Sub TimeOnlyParseExactExample() + ' Parse exact format + Dim exactTime = TimeOnly.ParseExact("5:00 pm", "h:mm tt", CultureInfo.InvariantCulture) + Console.WriteLine($"Exact time: {exactTime}") + + ' Parse 24-hour format + Dim militaryTime = TimeOnly.ParseExact("17:30:25", "HH:mm:ss", CultureInfo.InvariantCulture) + Console.WriteLine($"Military time: {militaryTime}") + + ' Parse with multiple possible formats + Dim timeFormats() As String = {"h:mm tt", "HH:mm", "H:mm"} + Dim flexibleTime = TimeOnly.ParseExact("2:30 PM", timeFormats, CultureInfo.InvariantCulture, DateTimeStyles.None) + Console.WriteLine($"Flexible time parse: {flexibleTime}") + End Sub + ' +End Module \ No newline at end of file diff --git a/docs/standard/base-types/snippets/parsing-datetime/vb/parsing-datetime.vbproj b/docs/standard/base-types/snippets/parsing-datetime/vb/parsing-datetime.vbproj new file mode 100644 index 0000000000000..773a87394dd64 --- /dev/null +++ b/docs/standard/base-types/snippets/parsing-datetime/vb/parsing-datetime.vbproj @@ -0,0 +1,9 @@ + + + + Exe + net10.0 + parsing_datetime + + + \ No newline at end of file diff --git a/docs/standard/datetime/how-to-use-dateonly-timeonly.md b/docs/standard/datetime/how-to-use-dateonly-timeonly.md index 8f1cfec99f39a..e4ebb68226a66 100644 --- a/docs/standard/datetime/how-to-use-dateonly-timeonly.md +++ b/docs/standard/datetime/how-to-use-dateonly-timeonly.md @@ -1,7 +1,7 @@ --- title: How to use DateOnly and TimeOnly description: Learn about the DateOnly and TimeOnly structures in .NET. -ms.date: 12/05/2024 +ms.date: 01/16/2026 dev_langs: - "csharp" - "vb" diff --git a/docs/standard/datetime/snippets/how-to-use-dateonly-timeonly/csharp/dateonlytimeonly.csproj b/docs/standard/datetime/snippets/how-to-use-dateonly-timeonly/csharp/dateonlytimeonly.csproj index 91b464afeacc1..dfb40caafcf9a 100644 --- a/docs/standard/datetime/snippets/how-to-use-dateonly-timeonly/csharp/dateonlytimeonly.csproj +++ b/docs/standard/datetime/snippets/how-to-use-dateonly-timeonly/csharp/dateonlytimeonly.csproj @@ -2,7 +2,7 @@ Exe - net8.0 + net10.0 enable enable diff --git a/docs/standard/datetime/snippets/how-to-use-dateonly-timeonly/vb/dateonlytimeonly.vbproj b/docs/standard/datetime/snippets/how-to-use-dateonly-timeonly/vb/dateonlytimeonly.vbproj index 92807d1660a18..378c6932de99a 100644 --- a/docs/standard/datetime/snippets/how-to-use-dateonly-timeonly/vb/dateonlytimeonly.vbproj +++ b/docs/standard/datetime/snippets/how-to-use-dateonly-timeonly/vb/dateonlytimeonly.vbproj @@ -3,7 +3,7 @@ Exe dateonlytimeonly - net8.0 + net10.0 diff --git a/docs/standard/datetime/snippets/timeprovider-overview/csharp/myproject.csproj b/docs/standard/datetime/snippets/timeprovider-overview/csharp/myproject.csproj index 694035b3acd5f..dfb40caafcf9a 100644 --- a/docs/standard/datetime/snippets/timeprovider-overview/csharp/myproject.csproj +++ b/docs/standard/datetime/snippets/timeprovider-overview/csharp/myproject.csproj @@ -2,7 +2,7 @@ Exe - net9.0 + net10.0 enable enable diff --git a/docs/standard/datetime/snippets/timeprovider-overview/vb/myproject.vbproj b/docs/standard/datetime/snippets/timeprovider-overview/vb/myproject.vbproj index cacdff353fc16..1309fca0c98e9 100644 --- a/docs/standard/datetime/snippets/timeprovider-overview/vb/myproject.vbproj +++ b/docs/standard/datetime/snippets/timeprovider-overview/vb/myproject.vbproj @@ -3,7 +3,7 @@ Exe ExampleProject - net9.0 + net10.0 diff --git a/docs/standard/datetime/timeprovider-overview.md b/docs/standard/datetime/timeprovider-overview.md index c105d1a2bdec0..b3322485d324a 100644 --- a/docs/standard/datetime/timeprovider-overview.md +++ b/docs/standard/datetime/timeprovider-overview.md @@ -1,7 +1,7 @@ --- title: What is the TimeProvider class description: Learn about the TimeProvider class in .NET and .NET Framework. TimeProvider provides an abstraction over time. -ms.date: 12/03/2024 +ms.date: 01/16/2026 ms.topic: overview dev_langs: - "csharp" @@ -14,7 +14,14 @@ helpviewer_keywords: # What is TimeProvider? - is an abstraction of time that provides a point in time as a type. By using `TimeProvider`, you ensure that your code is testable and predictable. `TimeProvider` was introduced in .NET 8 and is also available for .NET Framework 4.7+ and .NET Standard 2.0 as a NuGet package. + is an abstraction of time that provides a point in time as a type. By using `TimeProvider`, you ensure that your code is testable and predictable. `TimeProvider` is available on the following frameworks: + +| Framework | Notes | +|---|---| +| .NET 8+ | Included in the framework. | +| .NET 5 - .NET 7 | Provided in the [`Microsoft.Bcl.TimeProvider` NuGet package](https://www.nuget.org/packages/Microsoft.Bcl.TimeProvider). | +| .NET Framework 4.6.2+ | Provided in the [`Microsoft.Bcl.TimeProvider` NuGet package](https://www.nuget.org/packages/Microsoft.Bcl.TimeProvider). | +| .NET Standard 2.0 | Provided in the [`Microsoft.Bcl.TimeProvider` NuGet package](https://www.nuget.org/packages/Microsoft.Bcl.TimeProvider). | The class defines the following capabilities: @@ -28,16 +35,16 @@ The class defines the following capabilities: .NET provides an implementation of through the property, with the following characteristics: -- Date and time are calculated with and . +- Date and time are calculated by using and . - Timestamps are provided by . - Timers are implemented through an internal class and exposed as . -The following example demonstrates using to get the current date and time: +The following example shows how to use to get the current date and time: :::code language="csharp" source="./snippets/timeprovider-overview/csharp/Program.cs" id="GetLocal"::: :::code language="vb" source="./snippets/timeprovider-overview/vb/Program.vb" id="GetLocal"::: -The following example demonstrates capturing elapsed time with : +The following example shows how to capture elapsed time by using : :::code language="csharp" source="./snippets/timeprovider-overview/csharp/Program.cs" id="Timestamp"::: :::code language="vb" source="./snippets/timeprovider-overview/vb/Program.vb" id="Timestamp"::: @@ -54,12 +61,12 @@ The following list describes some of the capabilities of the and override members to control how time is provided. For example, the following class only provides a single date, the date of the moon landing: +While [FakeTimeProvider](#faketimeprovider-implementation) covers most scenarios that require predictability with time, you can still provide your own implementation. Create a new class that derives from and override members to control how time is provided. For example, the following class only provides a single date, the date of the moon landing: :::code language="csharp" source="./snippets/timeprovider-overview/csharp/MoonLandingTimeProviderPST.cs" id="CustomProvider"::: :::code language="vb" source="./snippets/timeprovider-overview/vb/MoonLandingTimeProviderPST.vb" id="CustomProvider"::: -If code using this class calls `MoonLandingTimeProviderPST.GetUtcNow`, the date of the moon landing in UTC is returned. If `MoonLandingTimeProviderPST.GetLocalNow` is called, the base class applies `MoonLandingTimeProviderPST.LocalTimeZone` to `GetUtcNow` and returns the moon landing date and time in the PST timezone. +If code using this class calls `MoonLandingTimeProviderPST.GetUtcNow`, the date of the moon landing in UTC is returned. If `MoonLandingTimeProviderPST.GetLocalNow` is called, the base class applies `MoonLandingTimeProviderPST.LocalTimeZone` to `GetUtcNow` and returns the moon landing date and time in the PST time zone. To demonstrate the usefulness of controlling time, consider the following example. Let's say that you're writing a calendar app that sends a greeting to the user when the app is first opened each day. The app says a special greeting when the current day has an event associated with it, such as the anniversary of the moon landing. @@ -80,7 +87,7 @@ And unit tests can be written to test specific scenarios, such as testing the an ## Use with .NET -Starting with .NET 8, the class is provided by the runtime library. Older versions of .NET or libraries targeting .NET Standard 2.0, must reference the [**Microsoft.Bcl.TimeProvider** NuGet package](https://www.nuget.org/packages/Microsoft.Bcl.TimeProvider/). +Starting with .NET 8, the runtime library provides the class. Older versions of .NET or libraries targeting .NET Standard 2.0 must reference the [`Microsoft.Bcl.TimeProvider` NuGet package](https://www.nuget.org/packages/Microsoft.Bcl.TimeProvider/). The following methods related to asynchronous programming work with `TimeProvider`: @@ -92,7 +99,7 @@ The following methods related to asynchronous programming work with `TimeProvide ## Use with .NET Framework - is implemented by the [**Microsoft.Bcl.TimeProvider** NuGet package](https://www.nuget.org/packages/Microsoft.Bcl.TimeProvider/). +The [`Microsoft.Bcl.TimeProvider` NuGet package](https://www.nuget.org/packages/Microsoft.Bcl.TimeProvider/) implements . Support for working with `TimeProvider` in asynchronous programming scenarios was added through the following extension methods: diff --git a/samples/snippets/csharp/how-to/conversions/Program.cs b/samples/snippets/csharp/how-to/conversions/Program.cs deleted file mode 100644 index 9d8454cff713c..0000000000000 --- a/samples/snippets/csharp/how-to/conversions/Program.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; - -namespace conversions -{ - class Program - { - static void Main(string[] args) - { - StringToDateTime.Examples(); - } - } -} diff --git a/samples/snippets/csharp/how-to/conversions/StringToDateTime.cs b/samples/snippets/csharp/how-to/conversions/StringToDateTime.cs deleted file mode 100644 index 77f134f3bf17b..0000000000000 --- a/samples/snippets/csharp/how-to/conversions/StringToDateTime.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System; -using System.Globalization; - -namespace conversions -{ - public static class StringToDateTime - { - public static void Examples() - { - FirstExample(); - GlobalExample(); - NoDefaultToCurrentDateTime(); - ParseExactExample(); - } - - static void FirstExample() - { - // - string dateInput = "Jan 1, 2009"; - var parsedDate = DateTime.Parse(dateInput); - Console.WriteLine(parsedDate); - // Displays the following output on a system whose culture is en-US: - // 1/1/2009 00:00:00 - // - } - - static void GlobalExample() - { - // - var cultureInfo = new CultureInfo("de-DE"); - string dateString = "12 Juni 2008"; - var dateTime = DateTime.Parse(dateString, cultureInfo); - Console.WriteLine(dateTime); - // The example displays the following output: - // 6/12/2008 00:00:00 - // - } - - static void NoDefaultToCurrentDateTime() - { - // - var cultureInfo = new CultureInfo("de-DE"); - string dateString = "12 Juni 2008"; - var dateTime = DateTime.Parse(dateString, cultureInfo, - DateTimeStyles.NoCurrentDateDefault); - Console.WriteLine(dateTime); - // The example displays the following output if the current culture is en-US: - // 6/12/2008 00:00:00 - // - } - - static void ParseExactExample() - { - // - var cultureInfo = new CultureInfo("en-US"); - string[] dateStrings = { " Friday, April 10, 2009", "Friday, April 10, 2009" }; - foreach (string dateString in dateStrings) - { - try - { - var dateTime = DateTime.ParseExact(dateString, "D", cultureInfo); - Console.WriteLine(dateTime); - } - catch (FormatException) - { - Console.WriteLine($"Unable to parse '{dateString}'"); - } - } - // The example displays the following output: - // Unable to parse ' Friday, April 10, 2009' - // 4/10/2009 00:00:00 - // - } - } -} \ No newline at end of file diff --git a/samples/snippets/visualbasic/how-to/conversions/Program.vb b/samples/snippets/visualbasic/how-to/conversions/Program.vb deleted file mode 100644 index 44d81451fcdf0..0000000000000 --- a/samples/snippets/visualbasic/how-to/conversions/Program.vb +++ /dev/null @@ -1,62 +0,0 @@ -Imports System.Globalization - -Module Program - Sub Main(args As String()) - FirstExample() - GlobalExample() - DefaultValueExample() - ParseExactExample() - End Sub - - Sub FirstExample() - ' - Dim MyString As String = "Jan 1, 2009" - Dim MyDateTime As DateTime = DateTime.Parse(MyString) - Console.WriteLine(MyDateTime) - ' Displays the following output on a system whose culture is en-US: - ' 1/1/2009 00:00:00 - ' - End Sub - - Sub GlobalExample() - ' - Dim MyCultureInfo As New CultureInfo("de-DE") - Dim MyString As String = "12 Juni 2008" - Dim MyDateTime As DateTime = DateTime.Parse(MyString, MyCultureInfo) - Console.WriteLine(MyDateTime) - ' The example displays the following output: - ' 6/12/2008 00:00:00 - ' - End Sub - - Sub DefaultValueExample() - ' - Dim MyCultureInfo As New CultureInfo("de-DE") - Dim MyString As String = "12 Juni 2008" - Dim MyDateTime As DateTime = DateTime.Parse(MyString, MyCultureInfo, - DateTimeStyles.NoCurrentDateDefault) - Console.WriteLine(MyDateTime) - ' The example displays the following output if the current culture is en-US: - ' 6/12/2008 00:00:00 - ' - End Sub - - Sub ParseExactExample() - ' - Dim MyCultureInfo As New CultureInfo("en-US") - Dim MyString() As String = {" Friday, April 10, 2009", "Friday, April 10, 2009"} - For Each dateString As String In MyString - Try - Dim MyDateTime As DateTime = DateTime.ParseExact(dateString, "D", - MyCultureInfo) - Console.WriteLine(MyDateTime) - Catch e As FormatException - Console.WriteLine("Unable to parse '{0}'", dateString) - End Try - Next - ' The example displays the following output: - ' Unable to parse ' Friday, April 10, 2009' - ' 4/10/2009 00:00:00 - ' - End Sub -End Module diff --git a/samples/snippets/visualbasic/how-to/conversions/conversions.vbproj b/samples/snippets/visualbasic/how-to/conversions/conversions.vbproj deleted file mode 100644 index a269962b552f0..0000000000000 --- a/samples/snippets/visualbasic/how-to/conversions/conversions.vbproj +++ /dev/null @@ -1,8 +0,0 @@ - - - - Exe - net8.0 - - -