Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Create new DateTime

Tags:

c#

I have a variable date in C# that I create using

var date = new DateTime(2000, 01, 01)

The result of the date is 01/01/2000 -> this is the month/date/year

I want the result is in format date/month/year

I know I can format this one.. But is there another way around that date will automatically in format date/month/year without manually format the date?

like image 507
gill23 Avatar asked Apr 04 '16 01:04

gill23


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C language?

C is a structured, procedural programming language that has been widely used both for operating systems and applications and that has had a wide following in the academic community. Many versions of UNIX-based operating systems are written in C.


2 Answers

If you look in the source code for the .NET framework for the DateTime type you'll find this line:

private ulong dateData;

That's how the DateTime is stored. There is no format.

From your code, new DateTime(2000, 01, 01), the underlying value for that DateTime is 630822816000000000.

But, when you go to display a date it would be exceedingly unhelpful if .ToString() produced 630822816000000000 instead of something like 01/01/2000.

So, still in the source, you'll find this override:

public override string ToString()
{
  return DateTimeFormat.Format(this, (string) null, DateTimeFormatInfo.CurrentInfo);
}

Effectively, the .ToString() method uses the current culture's info for formatting dates.

You can always do this to ensure you get consistent results:

var date = new DateTime(2000, 4, 16);

var us = date.ToString(CultureInfo.GetCultureInfo("en-us"));
var au = date.ToString(CultureInfo.GetCultureInfo("en-au"));

This results in the following formats respectively:

4/16/2000 12:00:00 AM
16/04/2000 12:00:00 AM
like image 63
Enigmativity Avatar answered Oct 03 '22 00:10

Enigmativity


In .net Date formats are based on your machine localization. So you have two options.

1) change your machine language and culture settings.

2) change threads CultureInfo to render date in correct formate.

For more information see https://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo(v=vs.110).aspx

like image 38
Saleem Avatar answered Oct 02 '22 23:10

Saleem