之前有个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 / ; remainSeconds = timestamp - minute * ; 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 / ( * ); remainSeconds = timestamp - hour * * ; 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 = * * ; var day = timestamp / daySeconds; remainSeconds = timestamp - day * daySeconds; return day + ;
} /// <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 = * * ;
//每月的总秒数
var monthDays = new int[] { * daySeconds, * daySeconds, * daySeconds, * daySeconds, * daySeconds, * daySeconds, * daySeconds, * daySeconds, * daySeconds, * daySeconds, * daySeconds, * daySeconds }; if (IsLeepYear(year))
monthDays[] = * daySeconds; var totalSeconds = ;
var month = ;
foreach (var second in monthDays)
{
month += ;
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 = , totalSeconds = ; while (true)
{
year += ;
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 * * * ;
else
return * * * ;
} /// <summary>
/// 判断闰年
/// </summary>
/// <param name="year"></param>
/// <returns></returns>
private static bool IsLeepYear(int year)
{ if (year % == && year % != )
return true;
else if (year % == )
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;
} }

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

  1. python转换时间戳和日期时间格式的转换

    [steven@txzxp2 seccenter]$ python Python 2.7.5 (default, Jul  8 2013, 09:48:59)  [GCC 4.8.1 20130603 ...

  2. python 日期、时间处理,各种日期时间格式/字符串之间的相互转换究竟是怎样的?

    模块函数说明 ''' date 日期对象,常用的属性有year,month,day time 时间对象,常用的属性有hour,minute,second,毫秒 datetime 日期时间对象,常用的属 ...

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

    /// java时间戳格式时间戳转为C#格式时间 public static DateTime GetTime(long timeStamp) { DateTime dtStart = TimeZon ...

  4. [php基础]Mysql日期函数:日期时间格式转换函数详解

    在PHP网站开发中,Mysql数据库设计中日期时间字段必不可少,由于Mysql日期函数输出的日期格式与PHP日期函数之间的日期格式兼容性不够,这就需要根据网站实际情况使用Mysql或PHP日期转换函数 ...

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

    mysql中UNIX时间戳与日期的相互转换 UNIX时间戳转换为日期用函数:FROM_UNIXTIME() select FROM_UNIXTIME(1410318106); 日期转换为UNIX时间戳 ...

  6. db2 日期时间格式

    db2日期和时间常用汇总 1.db2可以通过SYSIBM.SYSDUMMY1.SYSIBM.DUAL获取寄存器中的值,也可以通过VALUES关键字获取寄存器中的值. SELECT 'HELLO DB2 ...

  7. Android日期时间格式国际化

    公共类 的DateFormatSymbols 扩展对象 实现 Serializable接口 Cloneable接口 java.lang.Object的    ↳ java.text.DateForma ...

  8. Eclipse 改动凝视的 date time 日期时间格式,即${date}变量格式

    Eclipse 改动凝视的 date time 日期时间格式,即${date}变量格式 找到eclipse安装文件夹以下的plugins文件夹,搜索 org.eclipse.text ,找到一个jar ...

  9. js中时间戳与日期时间之间的相互转换

    1.时间戳转换为标准日期时间格式: function timeFormat(dateStr) { var date = new Date(dateStr); Y = date.getFullYear( ...

随机推荐

  1. 面试回顾——kafka

    关于消息队列的使用场景:https://www.cnblogs.com/linjiqin/p/5720865.html kafka: Topic Kafka将消息种子(Feed)分门别类 每一类的消息 ...

  2. 常用的stm32库函数

    //初始化的方式:先定义初始化机构体.再打开时钟使能.在对每一组GPIO口进行初始化. GPIO_InitTypeDef LED_GPIO; RCC_APB2PeriphClockCmd(RCC_AP ...

  3. 今天花了好长的时间终于把SecureCRT安装成功了 现在分享给大家 安装的步骤, 希望对大家用帮助

    转载地址:https://www.cnblogs.com/lianghe01/p/6618651.html 今天花了好长的时间终于把SecureCRT安装成功了 现在分享给大家 安装的步骤, 希望对大 ...

  4. .Net 中读写Oracle数据库常用两种方式

    .net中连接Oracle 的两种方式:OracleClient,OleDb转载 2015年04月24日 00:00:24 10820.Net 中读写Oracle数据库常用两种方式:OracleCli ...

  5. WMS接口平台配置培训

    供应链管理平台地址:https://twms.ninestargroup.com/ibus/#/processconfig?scShortcutld=3_17__1_303 WMS提供WSWMS固定的 ...

  6. spring boot 整合 elasticsearch 5.x

    spring boot与elasticsearch集成有两种方式.一种是直接使用elasticsearch.一种是使用data中间件. 本文只指针使用maven集成elasticsearch 5.x, ...

  7. EasyChat简易聊天室实现

    我是个技术新人,刚刚毕业,平时遇到问题都是在网上查找资料解决,而很多经验都来自园子,于是我也想有自己的园子,把自己的编程快乐与大家分享. 在学校学习的期间,老师带我们做winform,那时候我什么都不 ...

  8. python爬虫小说代码,可用的

    python爬虫小说代码,可用的,以笔趣阁为例子,python3.6以上,可用 作者的QQ:342290433,汉唐自远工程师 import requests import refrom lxml i ...

  9. GPL_LGPL

    LGPL 与GPL的区别   GPL(GNU General Public License) 我们很熟悉的Linux就是采用了GPL.GPL协议和BSD, Apache Licence等鼓励代码重用的 ...

  10. FortiGate高校图书馆SSLvpn配置案例

    1.组网及需求 某高校有一台FGT系列防火墙放置于互联网出口,拓扑如下图: 现需求通过组建sslvpn web代理模式和隧道模式以实现: 1.web代理模式:能访问 http://lib.xxxx.e ...