How to get current date in 'YYYY-MM-DD' format in ASP.NET?
Asked Answered
G

6

30

How to get current date in 'YYYY-MM-DD' format in ASP.NET ?

Guilty answered 17/2, 2011 at 13:8 Comment(1)
How to get the current date for what? What are you using the date for will you be displaying it. Is it just for one field or multiple fields. It would be a good idea to elaborate a little more.Blum
B
60

Which WebControl are you using? Did you try?

DateTime.Now.ToString("yyyy-MM-dd");
Beaujolais answered 17/2, 2011 at 13:9 Comment(2)
leave off the semicolon for VB.NET ;)Startle
if anyone need some more references i suggest to read and follow the tips over here : dotnetperls.com/datetime-format-vbnetScutcheon
C
7

The ToString method on the DateTime struct can take a format parameter:

var dateAsString = DateTime.Now.ToString("yyyy-MM-dd");
// dateAsString = "2011-02-17"

Documentation for standard and custom format strings is available on MSDN.

Cladophyll answered 17/2, 2011 at 13:9 Comment(0)
F
6

<%= DateTime.Now.ToString("yyyy-MM-dd") %>

Fibula answered 17/2, 2011 at 13:10 Comment(0)
M
4

try ToString method for your desirer format use

DateTime.Now.ToString("yyyy-MM-dd"); 


OR you can use it with your variable of DateTime type

dt.ToString("yyyy-MM-dd");


where dt is a DateTime variable

Mweru answered 17/2, 2011 at 13:9 Comment(1)
If you post code, XML or data samples, please highlight those lines in the text editor and click on the "code samples" button ( { } ) on the editor toolbar to nicely format and syntax highlight it!Unutterable
B
1

Might be worthwhile using the CultureInfo to apply DateTime formatting throughout the website. Insteado f running around formatting whever you have to.

CultureInfo.CurrentUICulture.DateTimeFormat.SetAllDateTimePatterns( ...

or

CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd"; 

Code should go somewhere in your Global.asax file

protected void Application_Start(){ ...
Blum answered 17/2, 2011 at 13:32 Comment(0)
F
1
var formatedDate = DateTime.Now.ToString("yyyy-MM-dd",System.Globalization.CultureInfo.InvariantCulture);

To ensure the user's local settings don't affect it

Foreleg answered 27/7, 2017 at 6:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.