Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert DateTime.Now to DateOnly in dd/mm/yyyy

Tags:

c#

I'm working with a DateOnly variable and I'm trying to get the DateTime.Now time in a dd/mm/yyyy format, however it's only returning the date on mm/dd/yyyy format.

I strictly need the current date in a dd/mm/yyyy format, and I haven't been able to figure it out how to.

This is an example how I'm working to convert the DateTime.Now to DateOnly type

public class Example
{
  public DateOnly? Date{get; set;}
}

public class Process1
{
  Example example = new Example();
  {
    example.Date= DateOnly.FromDateTime(DateTime.Now);
    //this is returning the current date in a mm/dd/yyyy format
  }
}
like image 392
Jositox Avatar asked Nov 26 '25 20:11

Jositox


2 Answers

Formatting can only be done by string not by date only.

save date in dateonly datatype

example.Date= DateOnly.FromDateTime(DateTime.Now);

but when you need specify format then use string like below


string s = example.Date.ToString("dd/M/yyyy", CultureInfo.InvariantCulture);
or 
s = example.Date.ToString("dd/MM/yyyy");

For More detail refer this Link

like image 66
Pradeep Kumar Avatar answered Nov 29 '25 08:11

Pradeep Kumar


I set the Date variable as a DateTime property in the Example Class :

public DateTime Date { get; set; } = DateTime.Now;

In the main code, i converted the Date property into a string and assigned it to dateOnly Variable:

string dateOnly = Convert.ToString(example.Date.ToString("dd-mm-yyyy"));

like image 28
JuniorProgrammer Avatar answered Nov 29 '25 09:11

JuniorProgrammer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!