Unix时间戳转日期时间格式,C#、Java、Python各语言实现!

之前有个Q上好友没事问我,怎么自己写Unix时间戳转日期时间?于是我就顺手写了个C#版本给他!最近想起来,就萌发多写几个语言的版本分享,权当练习思路外加熟悉另外两种语言。

先说转换步骤

  1. 先处理年份,从1970年开始处理,根据平年闰年的总秒数,先得到年,剩余的秒数再求月份;
  2. 根据剩余秒数求得月份,因为2月的缘故,同样需要处理平年闰年‘;
  3. 得天数,直接除以每天的总秒数,然后取得天;
  4. 取小时、分钟、秒;

Python版本:

# -*- coding: UTF-8 -*-
from datetime import datetime, tzinfo, timedelta
import pytz

class DateHelper:
    def unixTimestmpToDate(self,timestamp):
        #计算年
        (remainSeconds,year) = self.__get_year(timestamp)
        (remainSeconds,month) = self.__get_month(remainSeconds,year)
        (remainSeconds,day) = self.__get_day(remainSeconds)
        (remainSeconds,hour) = self.__get_hour(remainSeconds)
        (remainSeconds,minute) = self.__get_minute(remainSeconds)

        result = datetime(year, month, day, hour, minute, remainSeconds, 0, UTC(8))

        print result.strftime(‘%Y-%m-%d %H:%M:%S‘,)

    def __get_minute(self,timestamp):
        """
        计算分钟
        """
        min = timestamp / 60

        return (timestamp - min * 60, min)

    def __get_hour(self,timestamp):
        """
        计算小时
        """
        hour = timestamp / (60 * 60)

        return (timestamp - hour * 60 * 60, hour)

    def __get_day(self,timestamp):
        """
        计算天
        """
        #每天的秒数
        daySeconds = 24 * 60 * 60

        day = timestamp / daySeconds

        return (timestamp - day * daySeconds, day + 1)

    def __get_month(self, timestamp, year):
        """
        计算月份
        """
        #每天的秒数
        daySeconds = 24 * 60 * 60
        #每月的总秒数
        monthDays = [31 * daySeconds, 28 * daySeconds, 31 * daySeconds, 30 * daySeconds, 31 * daySeconds, 30 * daySeconds, 31 * daySeconds, 31 * daySeconds, 30 * daySeconds, 31 * daySeconds, 30 * daySeconds, 31 * daySeconds]

        if self.__is_leap_year(year):
            monthDays[1] = 29 * daySeconds

        totalSeconds = 0
        month = 0
        for second in monthDays:
            month +=1
            if second + totalSeconds > timestamp:
                break

            totalSeconds += second

        return (timestamp - totalSeconds, month)

    def __get_year(self,timestamp):
        """
        计算年份
        """
        year = 1969
        totalSeconds = 0

        while True:
            year +=1
            second = self.__get_year_seconds(year)
            #年份总秒数大于时间戳
            if totalSeconds + second > timestamp:
                break

            totalSeconds += second

        return (timestamp - totalSeconds,year)

    def __get_year_seconds(self,year):
        ‘‘‘
        得到每一年的总秒数
        ‘‘‘
        isLeapYear = self.__is_leap_year(year)

        if isLeapYear:
            return 366 * 24 * 60 * 60
        else:
            return 365 * 24 * 60 * 60

    def __is_leap_year(self,year):
        ‘‘‘
        判断是否闰年
        ‘‘‘
        if year % 4 == 0 and year % 100 != 0:
            return True
        elif year % 400 == 0:
            return True
        else:
            return False

class UTC(tzinfo):
    """UTC 时区创建"""
    def __init__(self,offset=0):
        self._offset = offset

    def utcoffset(self, dt):
        return timedelta(hours=self._offset)

    def tzname(self, dt):
        return "UTC +%s" % self._offset

    def dst(self, dt):
        return timedelta(hours=self._offset)

if __name__ == "__main__":
    datehelper = DateHelper()
    datehelper.unixTimestmpToDate(1483200000)

C#版本:

class DateHelper
    {
        /// <summary>
        /// unix时间戳转时间
        /// </summary>
        /// <param name="timestamp">时间戳</param>
        /// <returns></returns>
        public static DateTime UixTimestmpToDate(int timestamp)
        {
            int remainSeconds;
            int year = GetYear(timestamp, out remainSeconds);

            int seconds = remainSeconds;
            int month = GetMonth(seconds, year, out remainSeconds);

            // seconds = remainSeconds;
            int day = GetDay(remainSeconds, out remainSeconds);
            int hour = GetHours(remainSeconds, out remainSeconds);
            int minute = GetMinute(remainSeconds, out remainSeconds);

            return new DateTime(year, month, day, hour, minute, remainSeconds);
        }

        /// <summary>
        /// 计算分钟
        /// </summary>
        /// <param name="timestamp"></param>
        /// <param name="remainSeconds">剩余秒数</param>
        /// <returns></returns>
        private static int GetMinute(int timestamp, out int remainSeconds)
        {
            var minute = timestamp / 60;

            remainSeconds = timestamp - minute * 60;

            return minute;
        }

        /// <summary>
        /// 计算小时
        /// </summary>
        /// <param name="timestamp"></param>
        /// <param name="remainSeconds"></param>
        /// <returns></returns>
        private static int GetHours(int timestamp, out int remainSeconds)
        {
            var hour = timestamp / (60 * 60);

            remainSeconds = timestamp - hour * 60 * 60;

            return hour;
        }

        /// <summary>
        /// 计算日
        /// </summary>
        /// <param name="timestamp"></param>
        /// <param name="remainSeconds"></param>
        /// <returns></returns>
        private static int GetDay(int timestamp, out int remainSeconds)
        {
            var daySeconds = 24 * 60 * 60;

            var day = timestamp / daySeconds;

            remainSeconds = timestamp - day * daySeconds;

            return day + 1;
        }

        /// <summary>
        /// 计算月
        /// </summary>
        /// <param name="timestamp"></param>
        /// <param name="year"></param>
        /// <param name="remainSeconds"></param>
        /// <returns></returns>
        private static int GetMonth(int timestamp, int year, out int remainSeconds)
        {
            // 每天的秒数
            var daySeconds = 24 * 60 * 60;
            //每月的总秒数
            var monthDays = new int[] { 31 * daySeconds, 28 * daySeconds, 31 * daySeconds, 30 * daySeconds, 31 * daySeconds, 30 * daySeconds, 31 * daySeconds, 31 * daySeconds, 30 * daySeconds, 31 * daySeconds, 30 * daySeconds, 31 * daySeconds };

            if (IsLeepYear(year))
                monthDays[1] = 29 * daySeconds;

            var totalSeconds = 0;
            var month = 0;
            foreach (var second in monthDays)
            {
                month += 1;
                if (second + totalSeconds > timestamp)
                    break;

                totalSeconds += second;
            }
            remainSeconds = timestamp - totalSeconds;
            return month;
        }

        /// <summary>
        /// 计算年
        /// </summary>
        /// <param name="timestamp"></param>
        /// <param name="remainSeconds"></param>
        /// <returns></returns>
        private static int GetYear(int timestamp, out int remainSeconds)
        {
            int year = 1969, totalSeconds = 0;

            while (true)
            {
                year += 1;
                int second = GetYearSeconds(year);
                //年份总秒数大于时间戳
                if (totalSeconds + second > timestamp)
                    break;

                totalSeconds += second;

            }

            remainSeconds = timestamp - totalSeconds;

            return year;
        }

        /// <summary>
        /// 得到每一年的总秒数
        /// </summary>
        /// <param name="year"></param>
        /// <returns></returns>
        private static int GetYearSeconds(int year)
        {
            if (IsLeepYear(year))
                return 366 * 24 * 60 * 60;
            else
                return 365 * 24 * 60 * 60;
        }

        /// <summary>
        /// 判断闰年
        /// </summary>
        /// <param name="year"></param>
        /// <returns></returns>
        private static bool IsLeepYear(int year)
        {

            if (year % 4 == 0 && year % 100 != 0)
                return true;
            else if (year % 400 == 0)
                return true;
            else
                return false;
        }
/**
 * Created by chong on 2017/7/4.
 */
public class DateHelper {
    /**
     * unix时间戳转时间
     *
     * @param timestamp 时间戳
     * @return
     * @throws ParseException
     */
    public static Date uixTimestmpToDate(int timestamp) throws ParseException {
        int[] year = GetYear(timestamp);
        int[] month = GetMonth(year[1], year[0]);
        int[] day = GetDay(month[1]);
        int[] hour = GetHours(day[1]);
        int[] minute = GetMinute(hour[1]);

        String strDate = String.format("%d-%d-%d %d:%d:%d", year[0], month[0], day[0], hour[0], minute[0], minute[1]);

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //这次没有处理时区,所以直接输出的是UTC时间
        Date strtodate = formatter.parse(strDate);

        return strtodate;
    }

    /**
     * 计算分钟
     *
     * @param timestamp
     * @return
     */
    private static int[] GetMinute(int timestamp) {
        int minute = timestamp / 60;

        int remainSeconds = timestamp - minute * 60;

        return new int[]{minute, remainSeconds};
    }

    /**
     * 计算小时
     *
     * @param timestamp
     * @return
     */
    private static int[] GetHours(int timestamp) {
        int hour = timestamp / (60 * 60);

        int remainSeconds = timestamp - hour * 60 * 60;

        return new int[]{hour, remainSeconds};
    }

    /**
     * 计算日
     *
     * @param timestamp
     * @return
     */
    private static int[] GetDay(int timestamp) {
        int daySeconds = 24 * 60 * 60;

        int day = timestamp / daySeconds;

        int remainSeconds = timestamp - day * daySeconds;

        return new int[]{day + 1, remainSeconds};
    }

    /**
     * 计算月
     *
     * @param timestamp
     * @param year
     * @return
     */
    private static int[] GetMonth(int timestamp, int year) {
        // 每天的秒数
        int daySeconds = 24 * 60 * 60;
        //每月的总秒数
        int[] monthDays = new int[]{31 * daySeconds, 28 * daySeconds, 31 * daySeconds, 30 * daySeconds, 31 * daySeconds, 30 * daySeconds, 31 * daySeconds, 31 * daySeconds, 30 * daySeconds, 31 * daySeconds, 30 * daySeconds, 31 * daySeconds};

        if (IsLeepYear(year))
            monthDays[1] = 29 * daySeconds;

        int totalSeconds = 0, month = 0;
        for (int second : monthDays) {
            month += 1;
            if (second + totalSeconds > timestamp)
                break;

            totalSeconds += second;
        }
        int remainSeconds = timestamp - totalSeconds;
        return new int[]{month, remainSeconds};
    }

    /**
     * 计算年
     *
     * @param timestamp
     * @return
     */
    private static int[] GetYear(int timestamp) {
        int year = 1969, totalSeconds = 0;

        while (true) {
            year += 1;
            int second = GetYearSeconds(year);
            //年份总秒数大于时间戳
            if (totalSeconds + second > timestamp)
                break;

            totalSeconds += second;

        }
        int remainSeconds = timestamp - totalSeconds;

        return new int[]{year, remainSeconds};
    }

    /**
     * 得到每一年的总秒数
     *
     * @param year
     * @return
     */
    private static int GetYearSeconds(int year) {
        if (IsLeepYear(year))
            return 366 * 24 * 60 * 60;
        else
            return 365 * 24 * 60 * 60;
    }

    /**
     * 判断闰年
     *
     * @param year
     * @return
     */
    private static boolean IsLeepYear(int year) {

        if (year % 4 == 0 && year % 100 != 0)
            return true;
        else if (year % 400 == 0)
            return true;
        else
            return false;
    }

}
时间: 2024-10-12 14:30:03

Unix时间戳转日期时间格式,C#、Java、Python各语言实现!的相关文章

c# DateTime时间格式和JAVA时间戳格式相互转换

/// java时间戳格式时间戳转为C#格式时间 public static DateTime GetTime(long timeStamp) { DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); long lTime = timeStamp * 10000; TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNo

UNIX时间戳及日期的转换与计算

UNIX时间戳是保存日期和时间的一种紧凑简洁的方法,是大多数UNIX系统中保存当前日期和时间的一种方法,也是在大多数计算机语言中表示日期和时间的一种标准格式.以32位整数表示格林威治标准时间,例如,使用证书11230499325表示当前时间的时间戳.UNIX时间戳是从1970年1月1日零点(UTC/GMT的午夜)开始起到当前时间所经过的秒数.1970年1月1日零点作为所有日期计算的基础,这个日期通常成为UNIX纪元. 因为UNIX时间戳是一个32位的数字格式,所以特别适用于计算机处理,例如计算两

Android日期时间格式国际化

公共类 的DateFormatSymbols 扩展对象 实现 Serializable接口 Cloneable接口 java.lang.Object的    ? java.text.DateFormatSymbols 类概述 封装本地化的日期时间格式的数据,如几个月的名字,一周天的名字,和时区数据 的DateFormat 和 SimpleDateFormat 都使用 的DateFormatSymbols封装此信息. 通常情况下,你应该不能直接使用的DateFormatSymbols.相反,我们鼓

Eclipse 修改注释的 date time 日期时间格式,即${date}变量格式

Eclipse 修改注释的 date time 日期时间格式,即${date}变量格式 找到eclipse安装目录下面的plugins目录,搜索 org.eclipse.text ,找到一个jar包, 例如我找到的jar包为:org.eclipse.text_3.5.300.v20130515-1451.jar 然后打开它,找到这个类: org.eclipse.jface.text.templates.GlobalTemplateVariables 我们重写这个类就行了.(可反编译,也可以找到源

mysql UNIX时间戳与日期的相互转换

UNIX时间戳转换为日期用函数: FROM_UNIXTIME() select FROM_UNIXTIME(1156219870); 日期转换为UNIX时间戳用函数: UNIX_TIMESTAMP() Select UNIX_TIMESTAMP(’2006-11-04 12:23:00′); 例:mysql查询当天的记录数: $sql=”select * from message Where DATE_FORMAT(FROM_UNIXTIME(chattime),’%Y-%m-%d’) = DA

Sql日期时间格式转换

Sql日期时间格式转换 sql server2000中使用convert来取得datetime数据类型样式(全) 日期数据格式的处理,两个示例: CONVERT(varchar(16), 时间一, 20) 结果:2007-02-01 08:02/*时间一般为getdate()函数或数据表里的字段*/ CONVERT(varchar(10), 时间一, 23) 结果:2007-02-01 /*varchar(10)表示日期输出的格式,如果不够长会发生截取*/ 语句及查询结果:Select CONV

IOS --- 日期时间格式 转换

1.如何如何将一个字符串如" 20110826134106"装化为任意的日期时间格式,下面列举两种类型: NSString* string [email protected]"20110826134106"; NSDateFormatter*inputFormatter = [[[NSDateFormatter alloc] init]autorelease]; [inputFormattersetLocale:[[[NSLocale alloc] initWith

C#中 时间戳与普通时间格式的转换

时间戳,通常是一个字符序列,唯一地标识某一刻的时间. C#中关于时间戳与普通时间格式的相互转换如下 输出结果如下

DEDE日期时间格式大全

打造最全的CMS类教程聚合! 日期时间格式 (利用strftime()函数格式化时间) 首页: ([field:pubdate function='strftime("%m-%d",@me)'/])==(5-15) ([field:pubdate function='strftime("%b %d, %Y",@me)'/])==(May 15, 2008) 列表页: [field:pubdate function="GetDateTimeMK(@me)&q