Hi RydenChoi
I am making an assumption you are coding in C#.
Please see this example below (see it working here:
DateTime format dotNetFiddle example[
^])
using System;
using System.Collections.Generic;
namespace DateFormatTest
{
public class Program
{
private const string TODAY_FORMAT = "HH:mm";
private const string OTHER_DAY_FORMAT = "yyMMdd";
private List<dataitem> _Data = new List<dataitem>
{
new DataItem { Id = 1, When = DateTime.Today.AddDays(-1) },
new DataItem { Id = 2, When = DateTime.Now },
new DataItem { Id = 3, When = DateTime.Today.AddDays(1) },
new DataItem { Id = 4, When = null }
};
public void Main()
{
foreach(DataItem item in _Data)
{
Console.WriteLine("Id: " + Convert.ToString(item.Id) + ", When: " +FormatDate(item.When));
}
}
private string FormatDate(DateTime? val)
{
return val.HasValue ?
((DateTime)val).Date == DateTime.Today ? ((DateTime)val).ToString(TODAY_FORMAT) : ((DateTime)val).ToString(OTHER_DAY_FORMAT)
: "n/a";
}
}
public class DataItem
{
public int Id { get; set; }
public DateTime? When { get; set; }
}
}
1. My example data record: "DataItem" class. Notice I have created this to simulate your data record. Mine has a nullable DateTime property: "When". I have created a hardcoded list of DataItem to mock the database.
2. I have defined two string constants, for the two different date or time formats.
3. I have implemented a helper method "FormatDate" which takes parameter of type DateTime? (nullable). Depending on the value the constant date format is applied, or if the date value is null, then it returns 'n/a'. You may wish to return something different.
4. Pass the DateTime? value to the FormatDate method and do as you wish with it. In my example program it outputs the following
Id: 1, When: 160815
Id: 2, When: 09:49
Id: 3, When: 160817
Id: 4, When: n/a