java 以及 js 获取时间,日期,字符串,时间戳互转

本文详细介绍了如何使用JavaScript和Java进行时间的获取与转换,包括获取当前的年月日时分秒,毫秒数转换为日期格式,以及字符串与日期之间的相互转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

获取当前的年月日时分秒

var currTime = new Date();             //获取当前时间的毫秒数
var year = currTime.getFullYear();     //获取当前时间的年份
var month = currTime.getMonth() + 1;   //获取当前时间的月份,月份从0开始,所以需要加一
var day = currTime.getDate();          //获取当前时间的日期,getDay()可以获取星期几
var hour = currTime.getHours();        //获取当前时间的小时数
var minute = currTime.getMinutes();    //获取当前时间的分钟数
var second = currTime.getSeconds();    //获取当前时间的秒数

毫秒数转成年月日时分秒

//毫秒数转换成时间
var getCurrentTime = function(milliseconds){
    var myDate = new Date(milliseconds);
    var year = myDate.getFullYear();
    var month = myDate.getMonth() + 1;
    var day = myDate.getDate()
    var hour = myDate.getHours();
    var minute = myDate.getMinutes();
    var second = myDate.getSeconds();

    month = checkTime(month).toString();
    day = checkTime(day).toString();
    hour = checkTime(hour).toString();
    minute = checkTime(minute).toString();
    second = checkTime(second).toString();

    return year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second;
}
// 只有一位数字时添加“0”
var checkTime = function(i){
    if(i < 10){
        i = "0" + i;
    }
    return i;
}

java日期转换

时间戳、日期互转

//获取当前时间的时间戳  long类型
long l = System.currentTimeMillis();
Date de=new Date(l);
//String 类型
String l= "1435845268096";
//String转换long后再转换日期
Date de=new Date(Long.parseLong(l))
//日期转换时间戳
long timeStemp = de.getTime();

字符串转换日期

String strDate="2018-01-04 11:43:51";
//注意:SimpleDateFormat构造函数的样式与strDate的样式必须相符
SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
	//字符串转日期
	Date parse = sDateFormat.parse(strDate);
	//日期转字符串
	sDateFormat.format(parse)
} catch (ParseException e) {
	e.printStackTrace();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值