5

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
  }
}
Jositox
  • 53
  • 1
  • 7
  • 2
    `DateOnly` is a binary `struct`, if you want to represent it as a `string` use *formatting*, say `string text = Date.ToString(formatHere);` – Dmitry Bychenko Oct 26 '22 at 08:49
  • 2
    Neither `DateTime` nor `DateOnly` *have* a format. Formatting only comes into play when the value is converted to a string, either explicitly with `.ToString()` or implicitly in one of many ways (because you're viewing it in a debugger, feeding it to `Console.WriteLine`, etc.) – Jeroen Mostert Oct 26 '22 at 08:49
  • Does this answer your question? [C# DateTime to "YYYYMMDDHHMMSS" format](https://stackoverflow.com/questions/6121271/how-to-remove-time-portion-of-date-in-c-sharp-in-datetime-object-only) – Aliasghar Ahmadpour Oct 26 '22 at 08:52
  • @AliasgharAhmadpour that answer isn't relevant. `DateTime` and `DateOnly` have no format whatsoever, they're binary values. That answer shows how to format them into *strings* with a specific format. The types themselves store a tick or day offset since 0001-01-01 – Panagiotis Kanavos Oct 26 '22 at 08:55
  • Excuse me, i selected wrong link and link edited – Aliasghar Ahmadpour Oct 26 '22 at 08:57

2 Answers2

7

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

Pradeep Kumar
  • 1,193
  • 1
  • 9
  • 21
0

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"));