Skip to content

Commit 503e70c

Browse files
authored
Add datetime.parse and string.format C# samples (#3598)
* add datetime.parse and string.format samples
1 parent 0eadaeb commit 503e70c

18 files changed

+1224
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
using System;
2+
using System.Collections.Generic;
3+
4+
class ParseExamples
5+
{
6+
private static readonly KeyValuePair<string, Action>[] examples;
7+
private static string msg = null;
8+
9+
static ParseExamples()
10+
{
11+
examples = new KeyValuePair<string, Action>[] {
12+
new KeyValuePair<string, Action>(" 1. Forms of the string to be parsed", Strings.Parse),
13+
new KeyValuePair<string, Action>(" 2. Return value: The DateTime.Kind property", ReturnValue.Kind),
14+
new KeyValuePair<string, Action>(" 3. StyleFlags.RoundtripKind: Round-tripping a DateTime value", StyleFlag.RoundtripKind),
15+
new KeyValuePair<string, Action>(" 4. DateTime.Parse(String) overload", DateTimeParse1.ParseWithSingleArg),
16+
new KeyValuePair<string, Action>(" 5. DateTime.Parse(String, IFormatProvider) overload", DateTimeParse2.ParseWithTwoArgs),
17+
new KeyValuePair<string, Action>(" 6. DateTime.Parse(String, IFormatProvider, DateTimeStyles) overload", DateTimeParse3.ParseWithThreeArgs) };
18+
}
19+
20+
static void Main()
21+
{
22+
do
23+
{
24+
var choice = GetSelection(msg);
25+
26+
// Make sure this parses.
27+
bool success = Int32.TryParse(choice, out var nChoice);
28+
msg = "";
29+
30+
if (!success)
31+
{
32+
msg = $"'{choice}' is not a number between 0 and {examples.Length}.";
33+
}
34+
else
35+
{
36+
if (nChoice == 0)
37+
{
38+
return;
39+
}
40+
else if (nChoice < 0 || nChoice > examples.Length)
41+
{
42+
msg = $"Your selection must be between 0 and {examples.Length}.";
43+
}
44+
else
45+
{
46+
Console.WriteLine();
47+
examples[--nChoice].Value();
48+
49+
Console.Write("\nPress any key to continue...");
50+
Console.ReadKey(false);
51+
}
52+
53+
}
54+
} while (true);
55+
}
56+
57+
private static string GetSelection(string msg)
58+
{
59+
Console.Clear();
60+
Console.WriteLine();
61+
foreach (var example in examples)
62+
Console.WriteLine(example.Key);
63+
64+
if (!String.IsNullOrEmpty(msg))
65+
Console.WriteLine($"\n** {msg} **\n");
66+
67+
Console.Write("\nEnter the number of the example you wish to run and then press <Enter>. Or, press 0 to exit. ");
68+
var choice = Console.ReadLine();
69+
70+
return choice;
71+
}
72+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
---
2+
languages:
3+
- csharp
4+
products:
5+
- dotnet
6+
- dotnet-core
7+
page_type: sample
8+
name: DateTime.Parse examples
9+
urlFragment: datetime-parse
10+
description: "A .NET Core console application that contains different examples of using the DateTime.Parse method overloads."
11+
---
12+
# DateTime.Parse examples
13+
14+
This sample code is a .NET Core console application written in C#. It presents numbered options to the user that correspond to different date and time parsing examples.
15+
16+
## Sample prerequisites
17+
18+
This sample is written in C# and targets .NET Core 3.1. It requires the [.NET Core 3.1 SDK](https://dotnet.microsoft.com/download/dotnet-core/3.1).
19+
20+
## Build the sample
21+
22+
The source code includes an MSBuild project file for C# (a *.csproj* file) that targets .NET Core 3.1. After you download the *.zip* file containing the example code, create a directory and select **Download ZIP** to download the sample code files to your computer.
23+
24+
To build the sample:
25+
26+
1. Download the *.zip* file.
27+
1. Extrat the files in the *.zip* file to a directory of your choice.
28+
1. If you're using Visual Studio 2019:
29+
1. In Visual Studio, select **Open a project or solution** on the Start page. Or, select **File** > **Open** > **Project/Solution** from the top menu.
30+
1. Select **Debug** > **Start Debugging** from the top menu to build and launch the application.
31+
1. If you're working from the command line:
32+
1. Navigate to the directory that contains the sample.
33+
1. Enter the command `dotnet run` to build and launch the application.
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>netcoreapp3.1</TargetFramework>
6+
</PropertyGroup>
7+
8+
</Project>
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
using System;
2+
using System.Globalization;
3+
4+
public class DateTimeParse2
5+
{
6+
public static void ParseWithTwoArgs()
7+
{
8+
// Assume the current culture is en-US.
9+
// The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
10+
11+
// Use standard en-US date and time value.
12+
DateTime dateValue;
13+
string dateString = "2/16/2008 12:15:12 PM";
14+
try
15+
{
16+
dateValue = DateTime.Parse(dateString);
17+
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
18+
}
19+
catch (FormatException)
20+
{
21+
Console.WriteLine("Unable to convert '{0}'.", dateString);
22+
}
23+
24+
// Reverse month and day to conform to the fr-FR culture.
25+
// The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
26+
dateString = "16/02/2008 12:15:12";
27+
try
28+
{
29+
dateValue = DateTime.Parse(dateString);
30+
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
31+
}
32+
catch (FormatException)
33+
{
34+
Console.WriteLine("Unable to convert '{0}'.", dateString);
35+
}
36+
37+
// Call another overload of Parse to successfully convert string
38+
// formatted according to conventions of fr-FR culture.
39+
try
40+
{
41+
dateValue = DateTime.Parse(dateString, new CultureInfo("fr-FR", false));
42+
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
43+
}
44+
catch (FormatException)
45+
{
46+
Console.WriteLine("Unable to convert '{0}'.", dateString);
47+
}
48+
49+
// Parse string with date but no time component.
50+
dateString = "2/16/2008";
51+
try
52+
{
53+
dateValue = DateTime.Parse(dateString);
54+
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
55+
}
56+
catch (FormatException)
57+
{
58+
Console.WriteLine("Unable to convert '{0}'.", dateString);
59+
}
60+
}
61+
}
62+
// The example displays the following output to the console:
63+
// '2/16/2008 12:15:12 PM' converted to 2/16/2008 12:15:12 PM.
64+
// Unable to convert '16/02/2008 12:15:12'.
65+
// '16/02/2008 12:15:12' converted to 2/16/2008 12:15:12 PM.
66+
// '2/16/2008' converted to 2/16/2008 12:00:00 AM.
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
using System;
2+
using System.Globalization;
3+
4+
public class DateTimeParse3
5+
{
6+
public static void ParseWithThreeArgs()
7+
{
8+
string dateString;
9+
CultureInfo culture;
10+
DateTimeStyles styles;
11+
DateTime result;
12+
13+
// Parse a date and time with no styles.
14+
dateString = "03/01/2009 10:00 AM";
15+
culture = CultureInfo.CreateSpecificCulture("en-US");
16+
styles = DateTimeStyles.None;
17+
try
18+
{
19+
result = DateTime.Parse(dateString, culture, styles);
20+
Console.WriteLine("{0} converted to {1} {2}.",
21+
dateString, result, result.Kind.ToString());
22+
}
23+
catch (FormatException)
24+
{
25+
Console.WriteLine("Unable to convert {0} to a date and time.",
26+
dateString);
27+
}
28+
29+
// Parse the same date and time with the AssumeLocal style.
30+
styles = DateTimeStyles.AssumeLocal;
31+
try
32+
{
33+
result = DateTime.Parse(dateString, culture, styles);
34+
Console.WriteLine("{0} converted to {1} {2}.",
35+
dateString, result, result.Kind.ToString());
36+
}
37+
catch (FormatException)
38+
{
39+
Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
40+
}
41+
42+
// Parse a date and time that is assumed to be local.
43+
// This time is five hours behind UTC. The local system's time zone is
44+
// eight hours behind UTC.
45+
dateString = "2009/03/01T10:00:00-5:00";
46+
styles = DateTimeStyles.AssumeLocal;
47+
try
48+
{
49+
result = DateTime.Parse(dateString, culture, styles);
50+
Console.WriteLine("{0} converted to {1} {2}.",
51+
dateString, result, result.Kind.ToString());
52+
}
53+
catch (FormatException)
54+
{
55+
Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
56+
}
57+
58+
// Attempt to convert a string in improper ISO 8601 format.
59+
dateString = "03/01/2009T10:00:00-5:00";
60+
try
61+
{
62+
result = DateTime.Parse(dateString, culture, styles);
63+
Console.WriteLine("{0} converted to {1} {2}.",
64+
dateString, result, result.Kind.ToString());
65+
}
66+
catch (FormatException)
67+
{
68+
Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
69+
}
70+
71+
// Assume a date and time string formatted for the fr-FR culture is the local
72+
// time and convert it to UTC.
73+
dateString = "2008-03-01 10:00";
74+
culture = CultureInfo.CreateSpecificCulture("fr-FR");
75+
styles = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeLocal;
76+
try
77+
{
78+
result = DateTime.Parse(dateString, culture, styles);
79+
Console.WriteLine("{0} converted to {1} {2}.",
80+
dateString, result, result.Kind.ToString());
81+
}
82+
catch (FormatException)
83+
{
84+
Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
85+
}
86+
}
87+
}
88+
// The example displays the following output to the console:
89+
// 03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Unspecified.
90+
// 03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Local.
91+
// 2009/03/01T10:00:00-5:00 converted to 3/1/2009 7:00:00 AM Local.
92+
// Unable to convert 03/01/2009T10:00:00-5:00 to a date and time.
93+
// 2008-03-01 10:00 converted to 3/1/2008 6:00:00 PM Utc.
94+
95+
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
using System;
2+
using System.Globalization;
3+
4+
public class DateTimeParse1
5+
{
6+
public static void ParseWithSingleArg()
7+
{
8+
// Assume the current culture is en-US.
9+
// The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
10+
11+
// Use standard en-US date and time value.
12+
DateTime dateValue;
13+
string dateString = "2/16/2008 12:15:12 PM";
14+
try
15+
{
16+
dateValue = DateTime.Parse(dateString);
17+
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
18+
}
19+
catch (FormatException)
20+
{
21+
Console.WriteLine("Unable to convert '{0}'.", dateString);
22+
}
23+
24+
// Reverse month and day to conform to the fr-FR culture.
25+
// The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
26+
dateString = "16/02/2008 12:15:12";
27+
try
28+
{
29+
dateValue = DateTime.Parse(dateString);
30+
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
31+
}
32+
catch (FormatException)
33+
{
34+
Console.WriteLine("Unable to convert '{0}'.", dateString);
35+
}
36+
37+
// Call another overload of Parse to successfully convert string
38+
// formatted according to conventions of fr-FR culture.
39+
try
40+
{
41+
dateValue = DateTime.Parse(dateString, new CultureInfo("fr-FR", false));
42+
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
43+
}
44+
catch (FormatException)
45+
{
46+
Console.WriteLine("Unable to convert '{0}'.", dateString);
47+
}
48+
49+
// Parse string with date but no time component.
50+
dateString = "2/16/2008";
51+
try
52+
{
53+
dateValue = DateTime.Parse(dateString);
54+
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
55+
}
56+
catch (FormatException)
57+
{
58+
Console.WriteLine("Unable to convert '{0}'.", dateString);
59+
}
60+
}
61+
}
62+
// The example displays the following output to the console:
63+
// '2/16/2008 12:15:12 PM' converted to 2/16/2008 12:15:12 PM.
64+
// Unable to convert '16/02/2008 12:15:12'.
65+
// '16/02/2008 12:15:12' converted to 2/16/2008 12:15:12 PM.
66+
// '2/16/2008' converted to 2/16/2008 12:00:00 AM.
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
using System;
2+
3+
public class ReturnValue
4+
{
5+
public static void Kind()
6+
{
7+
string[] dateStrings = {"5/1/2008 7:34:42",
8+
"2008-05-01T07:34:42-5:00",
9+
"2008-05-01 7:34:42Z",
10+
"Thu, 01 May 2008 07:34:42 GMT"};
11+
12+
foreach (string dateString in dateStrings)
13+
{
14+
DateTime convertedDate = DateTime.Parse(dateString);
15+
Console.WriteLine($"Converted {dateString} to {convertedDate.Kind} time {convertedDate}");
16+
}
17+
}
18+
}
19+
20+
// These calls to the DateTime.Parse method display the following output:
21+
// Converted 2008-05-01T07:34:42-5:00 to Local time 5/1/2008 5:34:42 AM
22+
// Converted 2008-05-01 7:34:42Z to Local time 5/1/2008 12:34:42 AM
23+
// Converted Thu, 01 May 2008 07:34:42 GMT to Local time 5/1/2008 12:34:42 AM

0 commit comments

Comments
 (0)