Skip to content

Commit

Permalink
Add datetime.parse and string.format C# samples (#3598)
Browse files Browse the repository at this point in the history
* add datetime.parse and string.format samples
  • Loading branch information
gewarren authored May 21, 2020
1 parent 0eadaeb commit 503e70c
Show file tree
Hide file tree
Showing 18 changed files with 1,224 additions and 0 deletions.
72 changes: 72 additions & 0 deletions csharp/api/datetime.parse/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;

class ParseExamples
{
private static readonly KeyValuePair<string, Action>[] examples;
private static string msg = null;

static ParseExamples()
{
examples = new KeyValuePair<string, Action>[] {
new KeyValuePair<string, Action>(" 1. Forms of the string to be parsed", Strings.Parse),
new KeyValuePair<string, Action>(" 2. Return value: The DateTime.Kind property", ReturnValue.Kind),
new KeyValuePair<string, Action>(" 3. StyleFlags.RoundtripKind: Round-tripping a DateTime value", StyleFlag.RoundtripKind),
new KeyValuePair<string, Action>(" 4. DateTime.Parse(String) overload", DateTimeParse1.ParseWithSingleArg),
new KeyValuePair<string, Action>(" 5. DateTime.Parse(String, IFormatProvider) overload", DateTimeParse2.ParseWithTwoArgs),
new KeyValuePair<string, Action>(" 6. DateTime.Parse(String, IFormatProvider, DateTimeStyles) overload", DateTimeParse3.ParseWithThreeArgs) };
}

static void Main()
{
do
{
var choice = GetSelection(msg);

// Make sure this parses.
bool success = Int32.TryParse(choice, out var nChoice);
msg = "";

if (!success)
{
msg = $"'{choice}' is not a number between 0 and {examples.Length}.";
}
else
{
if (nChoice == 0)
{
return;
}
else if (nChoice < 0 || nChoice > examples.Length)
{
msg = $"Your selection must be between 0 and {examples.Length}.";
}
else
{
Console.WriteLine();
examples[--nChoice].Value();

Console.Write("\nPress any key to continue...");
Console.ReadKey(false);
}

}
} while (true);
}

private static string GetSelection(string msg)
{
Console.Clear();
Console.WriteLine();
foreach (var example in examples)
Console.WriteLine(example.Key);

if (!String.IsNullOrEmpty(msg))
Console.WriteLine($"\n** {msg} **\n");

Console.Write("\nEnter the number of the example you wish to run and then press <Enter>. Or, press 0 to exit. ");
var choice = Console.ReadLine();

return choice;
}
}
33 changes: 33 additions & 0 deletions csharp/api/datetime.parse/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
---
languages:
- csharp
products:
- dotnet
- dotnet-core
page_type: sample
name: DateTime.Parse examples
urlFragment: datetime-parse
description: "A .NET Core console application that contains different examples of using the DateTime.Parse method overloads."
---
# DateTime.Parse examples

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.

## Sample prerequisites

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).

## Build the sample

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.

To build the sample:

1. Download the *.zip* file.
1. Extrat the files in the *.zip* file to a directory of your choice.
1. If you're using Visual Studio 2019:
1. In Visual Studio, select **Open a project or solution** on the Start page. Or, select **File** > **Open** > **Project/Solution** from the top menu.
1. Select **Debug** > **Start Debugging** from the top menu to build and launch the application.
1. If you're working from the command line:
1. Navigate to the directory that contains the sample.
1. Enter the command `dotnet run` to build and launch the application.
8 changes: 8 additions & 0 deletions csharp/api/datetime.parse/datetime.parse.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

</Project>
66 changes: 66 additions & 0 deletions csharp/api/datetime.parse/parse_st_ifmt.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
using System;
using System.Globalization;

public class DateTimeParse2
{
public static void ParseWithTwoArgs()
{
// Assume the current culture is en-US.
// The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.

// Use standard en-US date and time value.
DateTime dateValue;
string dateString = "2/16/2008 12:15:12 PM";
try
{
dateValue = DateTime.Parse(dateString);
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}'.", dateString);
}

// Reverse month and day to conform to the fr-FR culture.
// The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
dateString = "16/02/2008 12:15:12";
try
{
dateValue = DateTime.Parse(dateString);
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}'.", dateString);
}

// Call another overload of Parse to successfully convert string
// formatted according to conventions of fr-FR culture.
try
{
dateValue = DateTime.Parse(dateString, new CultureInfo("fr-FR", false));
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}'.", dateString);
}

// Parse string with date but no time component.
dateString = "2/16/2008";
try
{
dateValue = DateTime.Parse(dateString);
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}'.", dateString);
}
}
}
// The example displays the following output to the console:
// '2/16/2008 12:15:12 PM' converted to 2/16/2008 12:15:12 PM.
// Unable to convert '16/02/2008 12:15:12'.
// '16/02/2008 12:15:12' converted to 2/16/2008 12:15:12 PM.
// '2/16/2008' converted to 2/16/2008 12:00:00 AM.
95 changes: 95 additions & 0 deletions csharp/api/datetime.parse/parse_st_ifmt_dtstyles.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
using System;
using System.Globalization;

public class DateTimeParse3
{
public static void ParseWithThreeArgs()
{
string dateString;
CultureInfo culture;
DateTimeStyles styles;
DateTime result;

// Parse a date and time with no styles.
dateString = "03/01/2009 10:00 AM";
culture = CultureInfo.CreateSpecificCulture("en-US");
styles = DateTimeStyles.None;
try
{
result = DateTime.Parse(dateString, culture, styles);
Console.WriteLine("{0} converted to {1} {2}.",
dateString, result, result.Kind.ToString());
}
catch (FormatException)
{
Console.WriteLine("Unable to convert {0} to a date and time.",
dateString);
}

// Parse the same date and time with the AssumeLocal style.
styles = DateTimeStyles.AssumeLocal;
try
{
result = DateTime.Parse(dateString, culture, styles);
Console.WriteLine("{0} converted to {1} {2}.",
dateString, result, result.Kind.ToString());
}
catch (FormatException)
{
Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
}

// Parse a date and time that is assumed to be local.
// This time is five hours behind UTC. The local system's time zone is
// eight hours behind UTC.
dateString = "2009/03/01T10:00:00-5:00";
styles = DateTimeStyles.AssumeLocal;
try
{
result = DateTime.Parse(dateString, culture, styles);
Console.WriteLine("{0} converted to {1} {2}.",
dateString, result, result.Kind.ToString());
}
catch (FormatException)
{
Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
}

// Attempt to convert a string in improper ISO 8601 format.
dateString = "03/01/2009T10:00:00-5:00";
try
{
result = DateTime.Parse(dateString, culture, styles);
Console.WriteLine("{0} converted to {1} {2}.",
dateString, result, result.Kind.ToString());
}
catch (FormatException)
{
Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
}

// Assume a date and time string formatted for the fr-FR culture is the local
// time and convert it to UTC.
dateString = "2008-03-01 10:00";
culture = CultureInfo.CreateSpecificCulture("fr-FR");
styles = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeLocal;
try
{
result = DateTime.Parse(dateString, culture, styles);
Console.WriteLine("{0} converted to {1} {2}.",
dateString, result, result.Kind.ToString());
}
catch (FormatException)
{
Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
}
}
}
// The example displays the following output to the console:
// 03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Unspecified.
// 03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Local.
// 2009/03/01T10:00:00-5:00 converted to 3/1/2009 7:00:00 AM Local.
// Unable to convert 03/01/2009T10:00:00-5:00 to a date and time.
// 2008-03-01 10:00 converted to 3/1/2008 6:00:00 PM Utc.


66 changes: 66 additions & 0 deletions csharp/api/datetime.parse/parse_string.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
using System;
using System.Globalization;

public class DateTimeParse1
{
public static void ParseWithSingleArg()
{
// Assume the current culture is en-US.
// The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.

// Use standard en-US date and time value.
DateTime dateValue;
string dateString = "2/16/2008 12:15:12 PM";
try
{
dateValue = DateTime.Parse(dateString);
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}'.", dateString);
}

// Reverse month and day to conform to the fr-FR culture.
// The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
dateString = "16/02/2008 12:15:12";
try
{
dateValue = DateTime.Parse(dateString);
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}'.", dateString);
}

// Call another overload of Parse to successfully convert string
// formatted according to conventions of fr-FR culture.
try
{
dateValue = DateTime.Parse(dateString, new CultureInfo("fr-FR", false));
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}'.", dateString);
}

// Parse string with date but no time component.
dateString = "2/16/2008";
try
{
dateValue = DateTime.Parse(dateString);
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}'.", dateString);
}
}
}
// The example displays the following output to the console:
// '2/16/2008 12:15:12 PM' converted to 2/16/2008 12:15:12 PM.
// Unable to convert '16/02/2008 12:15:12'.
// '16/02/2008 12:15:12' converted to 2/16/2008 12:15:12 PM.
// '2/16/2008' converted to 2/16/2008 12:00:00 AM.
23 changes: 23 additions & 0 deletions csharp/api/datetime.parse/returnvalue.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System;

public class ReturnValue
{
public static void Kind()
{
string[] dateStrings = {"5/1/2008 7:34:42",
"2008-05-01T07:34:42-5:00",
"2008-05-01 7:34:42Z",
"Thu, 01 May 2008 07:34:42 GMT"};

foreach (string dateString in dateStrings)
{
DateTime convertedDate = DateTime.Parse(dateString);
Console.WriteLine($"Converted {dateString} to {convertedDate.Kind} time {convertedDate}");
}
}
}

// These calls to the DateTime.Parse method display the following output:
// Converted 2008-05-01T07:34:42-5:00 to Local time 5/1/2008 5:34:42 AM
// Converted 2008-05-01 7:34:42Z to Local time 5/1/2008 12:34:42 AM
// Converted Thu, 01 May 2008 07:34:42 GMT to Local time 5/1/2008 12:34:42 AM
Loading

0 comments on commit 503e70c

Please sign in to comment.