tags:

views:

76

answers:

4

Say the current date is 1st Mar 2010, I want to display it like this...

20100301 so like first 4 digits = year, 2 digits = Month, 2 digits = day

is there an easy way to do this?

+2  A: 
var mydate = DateTime.Now; // Whatever you want.
mydate.ToString("yyyyMMdd");

Look at DateTimeFormatInfo for the other custom format strings you can use.

Reddog
+6  A: 

Something like

dateTimeObject.ToString("yyyyMMdd");

See String Format for DateTime

rahul
yeah I was gonna say... why upvote the only one of the 3 answers that was wrong :)
Luke Schafer
@Luke: because it was so obviously just a minor typo, your correct answer was not yet around, and the only remaining answer would not even compile as it was given first?
Fredrik Mörk
@Luke, it was just a typo.
rahul
@rahul and @Fredrik - while i agree, we pretty much answered at the same time, and after my answer no one had upvotes still. I suppose some people would have loaded the page in the time between this answer and mine, so I concede :)
Luke Schafer
thank you both for your help
RoboShop
+6  A: 

use format

yourdatetimeObj.ToString("yyyyMMdd");

Ref: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Luke Schafer
All the answers seemed to be the same now after further editing. Since you got it right the first time, I give you +1. :)
Syd
+1  A: 

You can either use the ToString() implementation of the DateTime class, like the examples already given, or use a format string to display it along with other information, like so:

var now = DateTime.Now;
var msg = String.Format("Now: {0:dd/MM/yyyy}", now);

Or

Console.Write("Now: {0:MM/dd/yyyy}", now);
Ioannis Karadimas