I am able to get date and time using:
DateTime now = DateTime.Now;
How can I get the current date and time separately in the DateTime format itself?
I am not using the DateTime picker dialog box in ASP.NET (C#).
This question is related to
c#
string now = Convert.ToString(DateTime.Now.ToShortDateString());
Console.WriteLine(now);
Console.ReadLine();
You can use following code to get the date and time separately.
DateTime now = DateTime.Now;
string date = now.GetDateTimeFormats('d')[0];
string time = now.GetDateTimeFormats('t')[0];
You can also, check the MSDN for more information.
There is no built-in date-only type in .NET.
The convention is to use a DateTime
with the time portion set to midnight.
The static DateTime.Today
property will give you today's date.
See, here you can get only date by passing a format string. You can get a different date format as per your requirement as given below for current date:
DateTime.Now.ToString("M/d/yyyy");
Result : "9/1/2015"
DateTime.Now.ToString("M-d-yyyy");
Result : "9-1-2015"
DateTime.Now.ToString("yyyy-MM-dd");
Result : "2015-09-01"
DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
Result : "2015-09-01 09:20:10"
For more details take a look at MSDN reference for Custom Date and Time Format Strings
DateTime.Now.ToString("dd/MM/yyyy");
Use DateTime.Today
property. It will return date component of DateTime.Now
. It is equivalent of DateTime.Now.Date
.
Current Time :
DateTime.Now.ToString("HH:mm:ss");
Current Date :
DateTime.Today.ToString("dd-MM-yyyy");
I think you need separately date parts like (day, Month, Year)
DateTime today = DateTime.Today;
Will not work for your case. You can get date separately so you don't need variable today
to be as a DateTime
Type, so lets just give today
variable int
Type because the day is only int. So today is 10 March 2020 then the result of
int today = DateTime.Today.Day;
int month = DateTime.Today.Month;
int year = DateTime.Today.Year;
MessageBox.Show(today.ToString()+ " - this is day. "+month.ToString()+ " - this is month. " + year.ToString() + " - this is year");
would be "10 - this is day. 3 - this is month. 2020 - this is year"
Use
txtdate.Text = DateTime.Today.ToString("dd-MM-yyyy");
for month
DateTime.Now.ToString("MM");
for day
DateTime.Now.ToString("dd");
for year
DateTime.Now.ToString("yyyy");
You can use DateTime.Now.ToShortDateString()
like so:
var test = $"<b>Date of this report:</b> {DateTime.Now.ToShortDateString()}";
Source: Stackoverflow.com