C# DateTime.Now formatting

maqskywalker
maqskywalker used Ask the Experts™
on
I'm using C# in a ASP.NET web application

In my C# code i have this line where I save today's date into a variable.

Todays date is 11/6/2017

With this code below. The value that gets saved in my variable looks like this: 11/6/2017 8:18:23 AM

// save todays date in a variable
DateTime testvar1 = DateTime.Now;

How do I format DateTime.Now so it save all the digits for the month and day.

I want the value saved in the variable to be this:
11/06/2017 8:18:23 AM

If today's date was 9/5/2017 the value saved in the variable would be this:
Basically add the zeros for single digit months and days.
09/05/2017 8:18:23 AM
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
Formatting a date is a display oriented task. If you're not doing something pertaining to display, then why do you care what format the date is in? A date is a date. Storage of that data should be done as the raw data (type). When you go to render the data to the screen (or a file, or a result from a web service, etc.), then stress about the format.
Database Expert
Awarded 2016
Top Expert 2016
Commented:
Please use full tested code for you -

String strDate = DateTime.Now.ToString();
DateTime datevalue = (Convert.ToDateTime(strDate.ToString()));
String dayy = datevalue.Day.ToString().PadLeft(2, "0");;
String monthm = datevalue.Month.ToString().PadLeft(2, "0");;
String yeary = datevalue.Year.ToString();
string finalDatetime = yeary + monthm + dayy ;

Open in new window


OUTPUT

2017/11/06 10:39 PM

Screen shot

EE_1.jpg
AndyAinscowFreelance programmer / Consultant

Commented:
// save todays date in a variable
DateTime testvar1 = DateTime.Now;

How do I format DateTime.Now so it save all the digits for the month and day.


What you have does what you ask for.  See the comment by Kaufmed.  A DateTime contains ALL the information, none is being lost.
Fully agree with Kaufmed and Andy above.
But whenever you ARE ready to convert (when you're displaying the variable), just use a custom format string, don't convert individually and then recombine.

DateTime.Now.ToString("MM/dd/yyyy h:mm tt")
anarki_jimbelSenior Developer

Commented:
Honestly, I'd never let to use the above "date string manipulation" code in my group. There are standard approaches to do the job, like shown by Snarf0001.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial