Formatting DateTime value in C#

I have a datetime variable like this:

DateTime date1 = DateTime.Now; // has 9.4.2014 01:12:35

I want to assign this to another datetime or change its value like this:

2014-04-09 13:12:35

How can I do? Thanks.

EDIT : I don't want string variable. I want it Datetime format.

Jon Skeet
people
quotationmark

The code you've written just assigns a value to a variable. It doesn't return anything, and it doesn't have any inherent string representation. A DateTime value is just a date/time. It can be displayed in whatever format you want, but that's not part of the value of the variable.

It sounds like you're wanting to convert it to a string in a particular format, which you should do with DateTime.ToString - but only when you really need to. Try to keep the value as a DateTime for as long as possible. Typically you only need to convert to a string in order to display the value to a user, or possibly to use it in something like JSON. (If you find yourself converting it to a string for database usage, you're doing it wrong - make sure your schema has an appropriate data type for the field, use a parameterized query, and set the parameter value to just the DateTime - nor formatting required.)

The format you've specified looks like it's meant to be a machine-readable one rather than a culture-specific one, so I'd suggest:

string text = date1.ToString("yyyy-MM-dd HH:mm:ss",
                             CultureInfo.InvariantCulture);

By specifying the invariant culture, we've said that the result shouldn't depend on the current culture (which otherwise it would) - this can make a big difference if the current culture uses a different calendar system, for example.

people

See more on this question at Stackoverflow