[Tutorial] Convert Unix time (Timestamp) to Normal time in Pawn
#1

I wrote a function that can help you to convert your unix time to normal time.

Function:
Code:
forward isLeap(y);
public isLeap(y){
    return ((y)%4==0&&((y)%100!=0||(y)%400==0));
}

stock unixtodate(timestamp)
{
	new rtrn[128];
    if(timestamp > 0) {
	    new year, dayInSeconds, daysInYear, daysInLYear, days, tmpDays, monthsInDays[12], month, day;
	    year = 1970;
	    dayInSeconds = 86400;
	    daysInYear = 365;
	    daysInLYear = daysInYear+1;
	    days = (timestamp/dayInSeconds);
	    tmpDays = days+1;
	    month = 11;

	    while(tmpDays>=daysInYear){
	        year++;
	        if(isLeap(year)){
	            tmpDays-=daysInLYear;
	        }
	        else{
	            tmpDays-=daysInYear;
	        }
	    }

	    if(isLeap(year)){
	        tmpDays--;
	        monthsInDays = {-1,30,59,90,120,151,181,212,243,273,304,334};
	    }
	    else{
	        monthsInDays = {0,31,59,90,120,151,181,212,243,273,304,334};
	    }

	    while(month>0){
	        if(tmpDays>monthsInDays[month]){
	            break;
	        }
	        month--;
	    }
	    day=tmpDays-monthsInDays[month];
	    month++;
		format(rtrn, sizeof(rtrn), "%d-%d-%d", year, month, day);
		return rtrn;
	}
	format(rtrn, sizeof(rtrn), "1970-1-1");
	return rtrn;
}
Example Usage:
Code:
printf("%s",unixtodate(1473939194));
Reply
#2

There are a couple of issues:

- 1st of a month (March to December) of a leap year, it gives the last day of the previous month.
- 31 December of a leap year, it gives 0 January of the next year.
- 31 December of not a leap year, it gives -1 January of the same year.

I also attempted to write the same and I managed to fix the above except that 1st March of a leap year is always given as 29th February. The weird thing is that when you get the days based on seconds and you remove the days from the previous years (starting from 1970), the days left sometimes go off.
Reply
#3

wrong section post it here https://sampforum.blast.hk/showthread.php?tid=281
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)