Convert Unix timestamp to DD/MM/YYYY HH:MM:SS format
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)
Input: T = 1595497956
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
- Convert given seconds into days by dividing them by the number of seconds in a day (86400) and store the remaining second.
- 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.
- Repeat step 2 until days become less than 365 (can not constitute a year).
- 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.
- 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).
- Repeat steps 5 until subtracting days of the month from extra days will give a negative result.
- If extra days are more than zero, increment month by 1.
- Now make use of the extra time from step 1.
- 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: