ABX
ABX

Reputation: 113

How to get current date in DDMMYY format and split them into DD, MM and YY using C#?

This is what i could write?

string text = string.Format("{0:d/MM/yy}", DateTime.Now.Date);
text = text.Replace("-", "");
char[] cString = text.ToCharArray();
string year = text.Substring(text.Length - 2);
string month = cString[2].ToString() + cString[3].ToString();
string day = cString[0].ToString() + cString[1].ToString();

Please help me find the mistake as it is not getting displayed correctly on my Win Form Application. It is showing 01 05 13 as 10 __ 13.

Upvotes: 1

Views: 7913

Answers (3)

p.s.w.g
p.s.w.g

Reputation: 149020

You can do that like this:

var date = DateTime.Now.Date;
var parts = date.ToString("d MM yy").Split(" "); // dd MM yy for 2-digit day
var year = parts[2];
var month = parts[1];
var day = parts[0];

But this seems even easier:

var date = DateTime.Now.Date;
var year = date.ToString("yy");
var month = date.ToString("MM");
var day = date.ToString("d");  // dd for 2-digit day

Upvotes: 5

ZanderAdam
ZanderAdam

Reputation: 434

Couldn't you do:

DateTime currDate = DateTime.Now;

string year = currDate.ToString("yy");
string month = currDate.ToString("MM");
string day  currDate.ToString("d");

or just

string date = DateTime.Now.ToString("d MM yy"); 

Upvotes: 0

Damith
Damith

Reputation: 63065

DateTime today = DateTime.Now;
int year = today.Year;
int month = today.Month
int day = today.Day;

Upvotes: 8

Related Questions