Format date in C#

In C#, you can format a date or time value in a form that you like by using the DateTimeOffset structure. The DateTimeOffset has a function called toString that accepts the string format for a specific form of date or time. This function is not called directly from the DateTimeOffset. Instead, it is called from the instance of the DateTimeOffset structure. You do not need to import any library to use the DateTimeOffset structure.

In the example code below, the toString function is used to format the current date in the form of "dd-MM-yyyy". The dd part means two-digit day.

The MM refers to two-digit month. And the yyyy represents four-digit year. To get the current date, you will use the Today property of the DateTime structure. You should note that the MM part can not be replaced by mm. You can not use DD to replace dd. And the yyyy can not replaced by the YYYY. They are not the same.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
   class Program
     static void Main(string[] args)
        DateTimeOffset dt = new DateTimeOffset(DateTime.Today);
        String df = "dd-MM-yyyy";

If you want a date like 30-Nov-2013, simply change the format string to dd-MMM-yyyy.
You also can change the format string to format a time value. For example, to format the current time in the form of "h:m:s", the format string would be h:m:s. The h, m, and s represent the hour, minute, and second respectively.

DateTimeOffset dt = new DateTimeOffset(DateTime.Now);
String df = "h:m:s";

Posted by: Dara | post date: 11-01-2013 | Subject: C# Programming Language

This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.