البرمجة

تنسيق تاريخ DateTime في C#

To change the format of a DateTime object in C# from “6/07/2016” to “6th July 2016,” you can use the ToString method with a custom date format string. Here’s how you can do it:

csharp
using System; class Program { static void Main() { DateTime date = new DateTime(2016, 7, 6); string formattedDate = date.ToString("d MMMM yyyy"); Console.WriteLine(formattedDate); } }

In this example, d represents the day of the month without a leading zero, MMMM represents the full month name, and yyyy represents the four-digit year. The output will be “6 July 2016”.

If you want to add the suffix to the day (e.g., “6th July 2016”), you’ll need to write a custom method to handle this, as there’s no built-in format specifier for this in C#. Here’s an example of how you could do it:

csharp
using System; class Program { static void Main() { DateTime date = new DateTime(2016, 7, 6); string formattedDate = FormatDateWithSuffix(date); Console.WriteLine(formattedDate); } static string FormatDateWithSuffix(DateTime date) { string daySuffix; switch (date.Day) { case 1: case 21: case 31: daySuffix = "st"; break; case 2: case 22: daySuffix = "nd"; break; case 3: case 23: daySuffix = "rd"; break; default: daySuffix = "th"; break; } return $"{date.Day}{daySuffix} {date:MMMM yyyy}"; } }

This will output “6th July 2016”.

المزيد من المعلومات

لتعديل تنسيق كائن DateTime في C# من “6/07/2016” إلى “6th July 2016″، يمكنك استخدام طريقة ToString مع سلسلة تنسيق تاريخ مخصصة. فيما يلي كيف يمكنك القيام بذلك:

csharp
using System; class Program { static void Main() { DateTime date = new DateTime(2016, 7, 6); string formattedDate = date.ToString("d MMMM yyyy"); Console.WriteLine(formattedDate); } }

في هذا المثال، يعبر d عن اليوم في الشهر بدون صفر مُسبَق، ويعبر MMMM عن اسم الشهر كاملاً، ويعبر yyyy عن السنة بأربعة أرقام. سيكون الإخراج “6 July 2016”.

إذا كنت ترغب في إضافة اللاحقة إلى اليوم (مثلًا، “6th July 2016”)، فسيتعين عليك كتابة طريقة مخصصة للتعامل مع ذلك، حيث لا يوجد مُحدِّد تنسيق مُدمَج لهذا في C#. فيما يلي مثال على كيفية القيام بذلك:

csharp
using System; class Program { static void Main() { DateTime date = new DateTime(2016, 7, 6); string formattedDate = FormatDateWithSuffix(date); Console.WriteLine(formattedDate); } static string FormatDateWithSuffix(DateTime date) { string daySuffix; switch (date.Day) { case 1: case 21: case 31: daySuffix = "st"; break; case 2: case 22: daySuffix = "nd"; break; case 3: case 23: daySuffix = "rd"; break; default: daySuffix = "th"; break; } return $"{date.Day}{daySuffix} {date:MMMM yyyy}"; } }

سيُخرِج هذا “6th July 2016”.

زر الذهاب إلى الأعلى