Search code examples
c#datetimetimeunix-timestampconverters

Get shortTimeDate from Unix format (C#)


I have time input data as below:

1536271200
1536184800
1536098400
1536012000
1535925600

I made quick Unix TimeConverter:

public static DateTime Converter(double ts)
{
        DateTime org= new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

        org = org.AddSeconds(ts);
        org = org.ToLocalTime();

        return org;
}

but after convert it return me date as below:

2018-09-10 00:00:00
2018-09-07 00:00:00
2018-09-06 00:00:00
2018-09-05 00:00:00
2018-09-04 00:00:00
2018-09-03 00:00:00

How to get shortDateFormat (YYYY-MM-DD)?


Solution

  • You can use .ToString(format) to get what ever format you want, and in this case it would be .ToString("yyyy-MM-dd"):

    public static string Converter(double ts)
    {
            DateTime org= new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    
            org = org.AddSeconds(ts);
            org = org.ToLocalTime();
    
            return org.ToString("yyyy-MM-dd");
    }
    

    and of course the function's return type must be string.