C# DateTime.Now formatting

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
LVL 1
maqskywalkerAsked:
Who is Participating?
 
Pawan KumarDatabase ExpertCommented:
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
0
 
käµfm³d 👽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.
0
 
AndyAinscowFreelance programmer / ConsultantCommented:
// 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.
0
 
Snarf0001Commented:
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")
1
 
anarki_jimbelCommented:
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.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.