Convert Unix timestamp to DD/MM/YYYY HH:MM:SS format

• Last Updated : 28 Jul, 2021

Given a Unix Timestamp T (in seconds) for a given point in time, the task is to convert it to human-readable format (DD/MM/YYYY HH:MM:SS)

Example:

Input: T = 1595497956
Output:23/7/2020 9:52:36
Explanation:In unix time T have 1595497956 seconds, So it makes total 50 years, 7 months, 23 days and 9 hours, 52 minutes and 36 second.

Input: T = 345234235
Output:9/12/1980 18:23:55

Approach:

1. Convert given seconds into days by dividing them by the number of seconds in a day (86400) and store the remaining second.
2. Since we count the number of days since Jan 1, 1970. Therefore, to calculate the current year keeping the concept of leap years in mind. Start in 1970. If the year is a leap year subtract 366 from days, otherwise subtract 365. Increase year by 1.
3. Repeat step 2 until days become less than 365 (can not constitute a year).
4. Add 1 to remaining days (extra days after calculating year) because the remaining days will give us days till the previous day, and we have to include the current day for DATE and MONTH calculation.
5. Increment the number of months by 1 and keep subtracting the number of days of the month from extra days (keeping in mind that February will have 29 days in a leap year and 28 otherwise).
6. Repeat steps 5 until subtracting days of the month from extra days will give a negative result.
7. If extra days are more than zero, increment month by 1.
8. Now make use of the extra time from step 1.
9. Calculate hours by dividing extra time by 3600, minutes by dividing the remaining seconds by 60, and seconds will be the remaining seconds.

Below is the implementation of the above approach: