Reputation: 173
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
}
}
Upvotes: 17
Views: 43024
Reputation: 11
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"));
Upvotes: 1
Reputation: 1526
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
Upvotes: 31