Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharpNotesForProfessionals.pdf
Скачиваний:
57
Добавлен:
20.05.2023
Размер:
6.12 Mб
Скачать

// Allow a leading space in the date string.

if (DateTime.TryParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, DateTimeStyles.AdjustToUniversal, out dateValue))

{

Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, dateValue.Kind);

}

else

{

Console.WriteLine("'{0}' is not in an acceptable format.", dateString);

}

Parse a string represengting UTC.

dateString = "2008-06-11T16:11:20.0904778Z";

if(DateTime.TryParseExact(dateString, "o", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue))

{

Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, dateValue.Kind);

}

else

{

Console.WriteLine("'{0}' is not in an acceptable format.", dateString);

}

if (DateTime.TryParseExact(dateString, "o", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out dateValue))

{

Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, dateValue.Kind);

}

else

{

Console.WriteLine("'{0}' is not in an acceptable format.", dateString);

}

Outputs

' 5/01/2009 8:30 AM' is not in

an

acceptable

format.

 

Converted ' 5/01/2009 8:30 AM'

to

5/1/2009 8:30:00 AM

(Unspecified).

Converted '5/01/2009 09:00' to

5/1/2009 9:00:00 AM (Unspecified).

'5/01/2009 09:00' is not in an

acceptable

format.

 

Converted '05/01/2009 01:30:42

PM

-05:00'

to

5/1/2009

11:30:42 AM (Local).

Converted '05/01/2009 01:30:42 PM

-05:00'

to

5/1/2009

6:30:42 PM (Utc).

Converted '2008-06-11T16:11:20.0904778Z' to 6/11/2008

9:11:20 AM (Local).

Converted '2008-06-11T16:11:20.0904778Z' to 6/11/2008

4:11:20 PM (Utc).

 

 

 

 

 

 

Section 19.12: DateTime.Add(TimeSpan)

// Calculate what day of the week is 36 days from this instant.

System.DateTime today = System.DateTime.Now; System.TimeSpan duration = new System.TimeSpan(36, 0, 0, 0); System.DateTime answer = today.Add(duration); System.Console.WriteLine("{0:dddd}", answer);

Section 19.13: Parse and TryParse with culture info

You might want to use it when parsing DateTimes from di erent cultures (languages), following example parses Dutch date.

GoalKicker.com – C# Notes for Professionals

86

DateTime dateResult;

var dutchDateString = "31 oktober 1999 04:20";

var dutchCulture = CultureInfo.CreateSpecificCulture("nl-NL"); DateTime.TryParse(dutchDateString, dutchCulture, styles, out dateResult);

// output {31/10/1999 04:20:00}

Example of Parse:

DateTime.Parse(dutchDateString, dutchCulture)

// output {31/10/1999 04:20:00}

Section 19.14: DateTime as initializer in for-loop

//This iterates through a range between two DateTimes

//with the given iterator (any of the Add methods)

DateTime start = new DateTime(2016, 01, 01);

DateTime until = new DateTime(2016, 02, 01);

//NOTICE: As the add methods return a new DateTime you have

//to overwrite dt in the iterator like dt = dt.Add()

for (DateTime dt = start; dt < until; dt = dt.AddDays(1))

{

Console.WriteLine("Added {0} days. Resulting DateTime: {1}", (dt - start).Days, dt.ToString());

}

Iterating on a TimeSpan works the same way.

Section 19.15:

DateTime.ParseExact(String, String, IFormatProvider)

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

Convert a specific format string to equivalent DateTime

Let's say we have a culture-specific DateTime string 08-07-2016 11:30:12 PM as MM-dd-yyyy hh:mm:ss tt format and we want it to convert to equivalent DateTime object

string str = "08-07-2016 11:30:12 PM";

DateTime date = DateTime.ParseExact(str, "MM-dd-yyyy hh:mm:ss tt", CultureInfo.CurrentCulture);

Convert a date time string to equivalent DateTime object without any specific culture format

Let's say we have a DateTime string in dd-MM-yy hh:mm:ss tt format and we want it to convert to equivalent DateTime object, without any specific culture information

string str = "17-06-16 11:30:12 PM";

DateTime date = DateTime.ParseExact(str, "dd-MM-yy hh:mm:ss tt", CultureInfo.InvariantCulture);

Convert a date time string to equivalent DateTime object without any specific culture format with di erent format

GoalKicker.com – C# Notes for Professionals

87

Let's say we have a Date string , example like '23-12-2016' or '12/23/2016' and we want it to convert to equivalent DateTime object, without any specific culture information

string date = '23-12-2016' or date = 12/23/2016';

string[] formats = new string[] {"dd-MM-yyyy","MM/dd/yyyy"}; // even can add more possible formats.

DateTime date = DateTime.ParseExact(date,formats, CultureInfo.InvariantCulture,DateTimeStyles.None);

NOTE : System.Globalization needs to be added for CultureInfo Class

Section 19.16: DateTime ToString, ToShortDateString, ToLongDateString and ToString formatted

using System;

 

public class Program

 

{

 

public static void Main()

 

{

 

var date = new DateTime(2016,12,31);

 

Console.WriteLine(date.ToString());

//Outputs: 12/31/2016 12:00:00 AM

Console.WriteLine(date.ToShortDateString()); //Outputs: 12/31/2016 Console.WriteLine(date.ToLongDateString()); //Outputs: Saturday, December 31, 2016 Console.WriteLine(date.ToString("dd/MM/yyyy")); //Outputs: 31/12/2016

}

}

Section 19.17: Current Date

To get the current date you use the DateTime.Today property. This returns a DateTime object with today's date. When this is then converted .ToString() it is done so in your system's locality by default.

For example:

Console.WriteLine(DateTime.Today);

Writes today's date, in your local format to the console.

GoalKicker.com – C# Notes for Professionals

88