js转换Date日期格式 / 时间转换
JS时间戳,毫秒级,格式化:
JavaScript Code复制内容到剪贴板
- function YYformatDate(timeStamp, type, auto) {
- type = type?type:"Y-m-d H:i:s";
- auto = auto?auto:false;
- let time = (timeStamp + '').length === 10 ? new Date(parseInt(timeStamp) * 1000) : new Date(parseInt(timeStamp));
- let _year = time.getFullYear();
- let _month = (time.getMonth() + 1) < 10 ? '0' + (time.getMonth() + 1) : (time.getMonth() + 1);
- let _date = time.getDate() < 10 ? '0' + time.getDate() : time.getDate();
- let _hours = time.getHours() < 10 ? '0' + time.getHours() : time.getHours();
- let _minutes = time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes();
- let _secconds = time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds();
- let formatTime = '';
- let distinctTime = new Date().getTime() - time.getTime();
- if (auto) {
- if (distinctTime <= (1 * 60 * 1000)) {
- // console.log('一分钟以内,以秒数计算');
- let _s = Math.floor((distinctTime / 1000) % 60);
- formatTime = _s + '秒前';
- } else if (distinctTime <= (1 * 3600 * 1000)) {
- // console.log('一小时以内,以分钟计算');
- let _m = Math.floor((distinctTime / (60 * 1000)) % 60);
- formatTime = _m + '分钟前';
- } else if (distinctTime <= (24 * 3600 * 1000)) {
- // console.log('一天以内,以小时计算');
- let _h = Math.floor((distinctTime / (60 * 60 * 1000)) % 24);
- formatTime = _h + '小时前';
- } else if (distinctTime <= (30 * 24 * 3600 * 1000)) {
- let _d = Math.floor((distinctTime / (24 * 60 * 60 * 1000)) % 30);
- formatTime = _d + '天前';
- // console.log('30天以内,以天数计算');
- } else {
- // 30天以外只显示年月日
- formatTime = _year + '-' + _month + '-' + _date;
- }
- } else {
- switch (type) {
- case 'Y-m-d H:i:s':
- formatTime = _year + '-' + _month + '-' + _date + ' ' + _hours + ':' + _minutes + ':' + _secconds;
- break;
- case 'Y-m-d H:i:s zh':
- formatTime = _year + '年' + _month + '月' + _date + '日 ' + _hours + ':' + _minutes + ':' + _secconds;
- break;
- case 'Y-m-d H:i':
- formatTime = _year + '-' + _month + '-' + _date + ' ' + _hours + ':' + _minutes;
- break;
- case 'Y-m-d H':
- formatTime = _year + '-' + _month + '-' + _date + ' ' + _hours;
- break;
- case 'Y-m-d':
- formatTime = _year + '-' + _month + '-' + _date;
- break;
- case 'Y-m-d zh':
- formatTime = _year + '年' + _month + '月' + _date + '日';
- break;
- case 'Y-m':
- formatTime = _year + '-' + _month;
- break;
- case 'Y':
- formatTime = _year;
- break;
- case 'm':
- formatTime = _month;
- break;
- case 'd':
- formatTime = _date;
- break;
- case 'H':
- formatTime = _hours;
- break;
- case 'i':
- formatTime = _minutes;
- break;
- case 's':
- formatTime = _secconds;
- break;
- default:
- formatTime = _year + '-' + _month + '-' + _date + ' ' + _hours + ':' + _minutes + ':' + _secconds;
- break;
- }
- }
- // 返回格式化的日期字符串
- return formatTime;
- }
JS时间戳转换
JavaScript Code复制内容到剪贴板
- /**
- * 时间戳格式化函数
- * @param {string} format 格式
- * @param {int} timestamp 要格式化的时间 默认为当前时间
- * @return {string} 格式化的时间字符串
- */
- function date(format, timestamp){
- var a, jsdate=((timestamp) ? new Date(timestamp*1000) : new Date());
- var pad = function(n, c){
- if((n = n + "").length < c){
- return new Array(++c - n.length).join("0") + n;
- } else {
- return n;
- }
- };
- var txt_weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
- var txt_ordin = {1:"st", 2:"nd", 3:"rd", 21:"st", 22:"nd", 23:"rd", 31:"st"};
- var txt_months = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
- var f = {
- // Day
- d: function(){return pad(f.j(), 2)},
- D: function(){return f.l().substr(0,3)},
- j: function(){return jsdate.getDate()},
- l: function(){return txt_weekdays[f.w()]},
- N: function(){return f.w() + 1},
- S: function(){return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th'},
- w: function(){return jsdate.getDay()},
- z: function(){return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0},
- // Week
- W: function(){
- var a = f.z(), b = 364 + f.L() - a;
- var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;
- if(b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b){
- return 1;
- } else{
- if(a <= 2 && nd >= 4 && a >= (6 - nd)){
- nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");
- return date("W", Math.round(nd2.getTime()/1000));
- } else{
- return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
- }
- }
- },
- // Month
- F: function(){return txt_months[f.n()]},
- m: function(){return pad(f.n(), 2)},
- M: function(){return f.F().substr(0,3)},
- n: function(){return jsdate.getMonth() + 1},
- t: function(){
- var n;
- if( (n = jsdate.getMonth() + 1) == 2 ){
- return 28 + f.L();
- } else{
- if( n & 1 && n < 8 || !(n & 1) && n > 7 ){
- return 31;
- } else{
- return 30;
- }
- }
- },
- // Year
- L: function(){var y = f.Y();return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0},
- //o not supported yet
- Y: function(){return jsdate.getFullYear()},
- y: function(){return (jsdate.getFullYear() + "").slice(2)},
- // Time
- a: function(){return jsdate.getHours() > 11 ? "pm" : "am"},
- A: function(){return f.a().toUpperCase()},
- B: function(){
- // peter paul koch:
- var off = (jsdate.getTimezoneOffset() + 60)*60;
- var theSeconds = (jsdate.getHours() * 3600) + (jsdate.getMinutes() * 60) + jsdate.getSeconds() + off;
- var beat = Math.floor(theSeconds/86.4);
- if (beat > 1000) beat -= 1000;
- if (beat < 0) beat += 1000;
- if ((String(beat)).length == 1) beat = "00"+beat;
- if ((String(beat)).length == 2) beat = "0"+beat;
- return beat;
- },
- g: function(){return jsdate.getHours() % 12 || 12},
- G: function(){return jsdate.getHours()},
- h: function(){return pad(f.g(), 2)},
- H: function(){return pad(jsdate.getHours(), 2)},
- i: function(){return pad(jsdate.getMinutes(), 2)},
- s: function(){return pad(jsdate.getSeconds(), 2)},
- //u not supported yet
- // Timezone
- //e not supported yet
- //I not supported yet
- O: function(){
- var t = pad(Math.abs(jsdate.getTimezoneOffset()/60*100), 4);
- if (jsdate.getTimezoneOffset() > 0) t = "-" + t; else t = "+" + t;
- return t;
- },
- P: function(){var O = f.O();return (O.substr(0, 3) + ":" + O.substr(3, 2))},
- //T not supported yet
- //Z not supported yet
- // Full Date/Time
- c: function(){return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P()},
- //r not supported yet
- U: function(){return Math.round(jsdate.getTime()/1000)}
- };
- return format.replace(/[\]?([a-zA-Z])/g, function(t, s){
- if( t!=s ){
- // escaped
- ret = s;
- } else if( f[s] ){
- // a date function exists
- ret = f[s]();
- } else{
- // nothing special
- ret = s;
- }
- return ret;
- });
- }
XML/HTML Code复制内容到剪贴板
- date('Y-m-d','1350052653');//很方便的将时间戳转换成了2012-10-11
- date('Y-m-d H:i:s','1350052653');//得到的结果是2012-10-12 22:37:33
JS获取当前时间,如:2020-08-05 16:17:31 星期四
JavaScript Code复制内容到剪贴板
- function getNowDate() {
- var date = new Date();
- var sign1 = "-";
- var sign2 = ":";
- var year = date.getFullYear() // 年
- var month = date.getMonth() + 1; // 月
- var day = date.getDate(); // 日
- var hour = date.getHours(); // 时
- var minutes = date.getMinutes(); // 分
- var seconds = date.getSeconds() //秒
- var weekArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'];
- var week = weekArr[date.getDay()];
- // 给一位数数据前面加 “0”
- if (month >= 1 && month <= 9) {
- month = "0" + month;
- }
- if (day >= 0 && day <= 9) {
- day = "0" + day;
- }
- if (hour >= 0 && hour <= 9) {
- hour = "0" + hour;
- }
- if (minutes >= 0 && minutes <= 9) {
- minutes = "0" + minutes;
- }
- if (seconds >= 0 && seconds <= 9) {
- seconds = "0" + seconds;
- }
- var currentdate = year + sign1 + month + sign1 + day + " " + hour + sign2 + minutes + sign2 + seconds + " " + week;
- return currentdate;
- }
- console.log(getNowDate());
JavaScript Code复制内容到剪贴板
- var myDate = new Date();
- myDate.getYear(); //获取当前年份(2位)
- myDate.getFullYear(); //获取完整的年份(4位,1970-????)
- myDate.getMonth(); //获取当前月份(0-11,0代表1月) // 所以获取当前月份是myDate.getMonth()+1;
- myDate.getDate(); //获取当前日(1-31)
- myDate.getDay(); //获取当前星期X(0-6,0代表星期天)
- myDate.getTime(); //获取当前时间(从1970.1.1开始的毫秒数)
- myDate.getHours(); //获取当前小时数(0-23)
- myDate.getMinutes(); //获取当前分钟数(0-59)
- myDate.getSeconds(); //获取当前秒数(0-59)
- myDate.getMilliseconds(); //获取当前毫秒数(0-999)
- myDate.toLocaleDateString(); //获取当前日期
- var mytime=myDate.toLocaleTimeString(); //获取当前时间
- myDate.toLocaleString( ); //获取日期与时间
- ==========================================================================
- JS获取当前时间戳的方法-JavaScript 获取当前毫秒时间戳有以下三种方法:
- var timestamp =Date.parse(new Date()); 结果:1280977330000 //不推荐; 毫秒改成了000显示
- var timestamp =(new Date()).valueOf(); 结果:1280977330748 //推荐;
- var timestamp=new Date().getTime(); 结果:1280977330748 //推荐;
- js中单独调用new Date(); 显示这种格式 Mar 31 10:10:43 UTC+0800 2012
- Math.round(new Date().getTime()/1000)
//getTime()返回数值的单位是毫秒 - 但是用new Date() 参与计算会自动转换为从1970.1.1开始的毫秒数
- --------------------------------------------------------------------------------------------------
- 将字符串形式的日期转换成日期对象
- var strTime="2011-04-16"; //字符串日期格式
- var date= new Date(Date.parse(strTime.replace(/-/g, "/"))); //转换成Data();
- --------------------------------------------------------------------------------------------------
- new Date() ; //参数可以为整数; 也可以为字符串; 但格式必须正确
- new Date(2009,1,1); //正确
- new Date("2009/1/1"); //正确
- new Date("2009-1-1"); //错误
- new Date( year, month, date, hrs, min, sec) 按给定的参数创建一日期对象
- 参数说明:
- year的值为:需设定的年份-1900。例如需设定的年份是1997则year的值应为97,即1997-1900的结果。所以Date中可设定的年份最小为1900;
- month的值域为0~11,0代表1月,11表代表12月;
- date的值域在1~31之间;
- hrs的值域在0~23之间。从午夜到次日凌晨1点间hrs=0,从中午到下午1点间hrs=12;
- min和sec的值域在0~59之间。
- 例 Date day=new Date(11,3,4);
- //day中的时间为:04-Apr-11 12:00:00 AM
- 另外,还可以给出不正确的参数。
- 例 设定时间为1910年2月30日,它将被解释成3月2日。
- Date day=new Date(10,1,30,10,12,34);
- System.out.println("Day's date is:"+day);
- //打印结果为:Day's date is:Web Mar 02 10:13:34 GMT+08:00 1910
有时候做项目会用到js的date日期格式,因为Date()返回的格式不是我们需要的,
Date()返回格式:
Thu Mar 19 2015 12:00:00 GMT+0800 (中国标准时间)
而我们则需要这样的格式:
2015-3-19 12:00:00
除非是在后台处理好时间格式,然后在页面直接显示。
那如何用js格式化date日期值呢?
1.日期格式转为日期标准字符串:2015-03-19
JavaScript Code复制内容到剪贴板
- var formatDate = function (date) {
- var y = date.getFullYear();
- var m = date.getMonth() + 1;
- m = m < 10 ? '0' + m : m;
- var d = date.getDate();
- d = d < 10 ? ('0' + d) : d;
- return y + '-' + m + '-' + d;
- };
2.js方法返回值:2015-03-19 12:00:00
JavaScript Code复制内容到剪贴板
- var formatDateTime = function (date) {
- var y = date.getFullYear();
- var m = date.getMonth() + 1;
- m = m < 10 ? ('0' + m) : m;
- var d = date.getDate();
- d = d < 10 ? ('0' + d) : d;
- var h = date.getHours();
- h=h < 10 ? ('0' + h) : h;
- var minute = date.getMinutes();
- minute = minute < 10 ? ('0' + minute) : minute;
- var second=date.getSeconds();
- second=second < 10 ? ('0' + second) : second;
- return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
- };
调用:formatDate(Date()) formatDate(Date())
3.时间戳转为日期格式
JavaScript Code复制内容到剪贴板
- //时间戳转日期格式
- var formatDateTime3 = function(time, format){
- var t = new Date(time);
- var tf = function(i){return (i < 10 ? '0' : '') + i};
- return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a){
- switch(a){
- case 'yyyy':
- return tf(t.getFullYear());
- break;
- case 'MM':
- return tf(t.getMonth() + 1);
- break;
- case 'mm':
- return tf(t.getMinutes());
- break;
- case 'dd':
- return tf(t.getDate());
- break;
- case 'HH':
- return tf(t.getHours());
- break;
- case 'ss':
- return tf(t.getSeconds());
- break;
- }
- })
- };
4.时间格式字符串转为时间戳(毫秒)
JavaScript Code复制内容到剪贴板
- var time1=‘2016-01-01 17:22:37’;
- var date=new Date(time1.replace(/-/g, '/')); //开始时间
- var time2=date.getTime();
如何将2015-03-12 12:00 转换成标准时间()?
Thu Mar 19 2015 12:00:00 GMT+0800 (中国标准时间)
js方法返回值:Thu Mar 19 2015 12:00:00 GMT+0800 (中国标准时间)
JavaScript Code复制内容到剪贴板
- var parserDate = function (date) {
- var t = Date.parse(date);
- if (!isNaN(t)) {
- return new Date(Date.parse(date.replace(/-/g, "/")));
- } else {
- return new Date();
- }
- };
调用:parserDate("2015-03-19 12::00:00")
5.判断时间间隔不超过24个小时
JS中字符转日期
var remindTime = "2008-04-02 10:08:44";
直接new Date(remindTime ) 即可。
var date1=new Date("2004/09/16 20:08:00");
var date2=new Date("2004/09/17 20:08:00");
var date3=(date2.getTime()-date1.getTime())/1000; //相差秒数
JavaScript Code复制内容到剪贴板
- String tt="2015-11-25 18:18:18 - 2015-11-26 12:09:27";
- String start=tt.substring(0,19);
- String end=tt.substring(22,tt.length());
- var startTime=$("#searchDateRange").val().substring(0,19).replace(/-/g, '/');
- var endTime=$("#searchDateRange").val().substring(22,41).replace(/-/g, '/');
- var date1=new Date(startTime); //开始时间
- var date2=new Date(endTime); //结束时间
- var date3=date2.getTime()-date1.getTime() //时间差的毫秒数
- if(date3>60*60*24*1000){
- alert("开始时间与结束时间间隔大于24小时!");
- return false;
- }
JavaScript Code复制内容到剪贴板
- getStatusByPublishAudit(startTime,endTime){
- // 已发布状态下,根据开始时间和结束时间判断结果
- let currentTime = Math.round(new Date().getTime()/1000);
- let txt = "";
- startTime = this.getTimeStamp(startTime);
- endTime = this.getTimeStamp(endTime);
- if(startTime > currentTime){
- txt = "已发布未开始"
- }else if(endTime < currentTime){
- txt = "已结束"
- }else{
- txt = "已发布进行中"
- };
- return txt;
- }
JavaScript Code复制内容到剪贴板
- if( (startTime < currentTime) && (endTime > currentTime) ){
- // 进行中单独判断
- }
下一篇 upload 上传图片(简易)