Home Web Front-end JS Tutorial Detailed explanation of javascript date operations (organized by Script House)_Time and date

Detailed explanation of javascript date operations (organized by Script House)_Time and date

May 16, 2016 pm 03:40 PM
js Date operations

它是一个内置对象——而不是其它对象的属性,允许用户执行各种使用日期和时间的过程。

方法:分为得到时间方法、设置时间方法和转换时间方法

得到时间方法:
  getDate() 查看Date对象并返回日期
  getDay() 返回星期几
  getHours() 返回小时数
  getMinutes() 返回分钟数
  getMonth() 返回月份值
  getSeconds() 返回秒数
  getTime() 返回完整的时间
  getYear() 返回年份

js中的日期时间函数具体使用注意事项: 月份获取的时候会-1. 例如当前是12月份,获取的数字就是11

var date = new Date();
date.getYear();        //获取年份(2位)
date.getFullYear();    //获取完整的年份(4位,1970-)
date.getMonth();       //获取月份(0-11,0代表1月,所以在显示当前时间的时候需要date.getMonth() + 1)
date.getDate();        //获取日(1-31)
date.getDay();         //获取星期?(0-6,0代表星期天)
date.getTime();        //获取时间(从1970.1.1开始的毫秒数)
date.getHours();       //获取小时数(0-23)
date.getMinutes();     //获取分钟数(0-59)
date.getSeconds();     //获取秒数(0-59)
date.getMilliseconds();    //获取毫秒数(0-999)
date.toLocaleString();        //获取日期与时间
  

设置时间方法:
  setDate() 改变Date对象的日期
  setHours() 改变小时数
  setMinutes() 改变分钟数
  setMonth() 改变月份
  setSeconds() 改变秒数
  setTime() 改变完整的时间
  setYear() 改变年份

转换时间方法:

  toGMTString() 把Date对象的日期(一个数值)转变成一个GMT时间字符串,返回类似下面的值:Weds,15 June l997 14:02:02 GMT(精确的格式依赖于计算机上所运行的操作系统而变)
  toLocaleString() 把Date对象的日期(一个数值)转变成一个字符串,使用所在计算机上配置使用的特定日期格式
  UTC() 使用Date UTC(年、月、日、时、分、秒),以自从1970年1月1日00:00:00(其中时、分、秒是可选的)以来的毫秒数的形式返回日期

几个需要注意的地方:

最重要的一点就是考虑到多浏览器的兼容性。需要按如下格式获取日期比较好

var timestart = '2015-09-05'; 
var timeend = '2015-09-06';
var time1 = (timestart+' 00:00:00').toString();
var time2 = (timeend+' 23:59:59').toString();
timestart = new Date(Date.parse(time1.replace(/-/g,"/"))).getTime();
timeend = new Date(Date.parse(time2.replace(/-/g,"/"))).getTime();
Copy after login

脚本之家小编为大家提供一个刚写的,在某一个时间段才显示的广告代码

<script type="text/javascript">
var timestart = '2015-09-05'; 
var timeend = '2015-09-06';
var time1 = (timestart+' 16:00:00').toString(); 
var time2 = (timeend+' 16:00:00').toString(); 
timestart = new Date(Date.parse(time1.replace(/-/g,"/"))).getTime(); 
timeend = new Date(Date.parse(time2.replace(/-/g,"/"))).getTime();
var nowtime=new Date().getTime();
if (nowtime>timestart && nowtime<timeend)
{
document.write("广告");
}
</script>
Copy after login

1、得到日期和年和设置日期和年时间,其中很怪的问题就是不能对月份进行设置(比较的怪):

<script language="javascript"> 
d = new Date(); 
alert(d.toLocaleString()); 
d.setDate(25); 
alert(d.toLocaleString()); 
d.setYear(2000); 
alert(d.toLocaleString()); 
</script> 
Copy after login

2、获得年的时候最好用getFullYear()方法来做
3、由于针对月份,JS是从0开始的,因此需要对月份进行操作时要加1

下面是几个关于时间的经典而且经常会用到的例子,希望对大家会有提高的。谢谢继续关注该帖子。。。

1、将2005-8-5转换成2005-08-05格式

<script language="javascript"> 
var strDate = '2005-8-5'; 
window.alert(strDate.replace(/\b(\w)\b/g, '0$1')); 
</script> 
Copy after login

2、得到间隔天数

<script type="text/javascript"> 
<!-- 
alert("间隔天数为:"+(new Date('2005/8/15')-new Date('2003/9/18'))/1000/60/60/24+"天") 
//--> 
</script> 
Copy after login

3、得到间隔时间

<script> 
var d1=new Date("2004/09/16 20:08:00"); 
var d2=new Date("2004/09/16 10:18:03"); 
var d3=d1-d2; 
var h=Math.floor(d3/3600000); 
var m=Math.floor((d3-h*3600000)/60000); 
var s=(d3-h*3600000-m*60000)/1000; 
alert("相差"+h+"小时"+m+"分"+s+"秒"); 
</script> 
Copy after login

4、得到今天的日期

<script language="javascript"> 
d = new Date(); 
alert(d.getFullYear()+"年"+(d.getMonth()+1)+"月"+d.getDate()+"日"); 
</script> 
Copy after login


6、数字日期转汉字

<html> 
<head> 
<title> New Document </title> 
</head>
<body> 
<script language=javascript> 
Date.prototype.getRead = function() 
{ 
var values = new Array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九"); 
var returnValue, temp; 
returnValue = this.getYear()+"年"; 
temp = (this.getMonth()+1)+"月"+this.getDate()+"日"; 
temp = temp.replace(/(\d)(\d)/g,"$1十$2").replace(/1十/g,"十").replace(/十0/g,"十"); 
returnValue += temp; 
returnValue = returnValue.replace(/\d/g, function(sts){return values[parseInt(sts)]}); 
return returnValue; 
} 
var t=new Date(); 
document.write(t.getRead()); 
</script> 
</body> 
</html>
Copy after login

7、得到前N天或后N天的日期


方法一:

<script type="text/javascript"> 
function showdate(n) 
{ 
var uom = new Date(new Date()-0+n*86400000); 
uom = uom.getFullYear() + "-" + (uom.getMonth()+1) + "-" + uom.getDate(); 
return uom; 
} 

window.alert("今天是:"+showdate(0)); 
window.alert("昨天是:"+showdate(-1)); 
window.alert("明天是:"+showdate(1)); 
window.alert("10天前是:"+showdate(-10)); 
window.alert("5天后是:"+showdate(5)); 
</script> 
Copy after login

方法二:

<script type="text/javascript"> 
function showdate(n) 
{ 
var uom = new Date(); 
uom.setDate(uom.getDate()+n); 
uom = uom.getFullYear() + "-" + (uom.getMonth()+1) + "-" + uom.getDate(); 
return uom; 
} 

window.alert("今天是:"+showdate(0)); 
window.alert("昨天是:"+showdate(-1)); 
window.alert("明天是:"+showdate(1)); 
window.alert("10天前是:"+showdate(-10)); 
window.alert("5天后是:"+showdate(5)); 
</script> 
Copy after login

方法三(不好意思,这个用vsscript做的,仅作为学习使用,不建议网页中使用,毕竟 IE only):

<script language="vbscript"> 
function showdate(n) 
showdate=dateadd("d",date(),n) 
end function 
msgbox "今天是:"&showdate(0) 
msgbox "昨天是:"&showdate(-1) 
msgbox "明天是:"&showdate(1) 
msgbox "十天前是:"&showdate(-10) 
msgbox "五天后是:"&showdate(5) 
</script> 
Copy after login

方法四:

<script language="Javascript"> 
Date.prototype.getDays=function(){ 
var _newDate=new Date(); 
_newDate.setMonth(_newDate.getMonth()+1); 
_newDate.setDate(0); 
$_days=_newDate.getDate(); 
delete _newDate; 
return $_days; 
} 
function showdate(n) 
{ 
var uom = new Date(); 
uom.setDate(uom.getDate()+n); 
uom = uom.getFullYear() + "-" + (uom.getMonth()+1) + "-" + uom.getDate()+"\n星期"+('天一二三四五六'.charAt(uom.getDay()))+"\n本月有"+ uom.getDays()+"天"; 
return uom; 
} 

window.alert("今天是:"+showdate(0)); 
window.alert("昨天是:"+showdate(-1)); 
window.alert("明天是:"+showdate(1)); 
window.alert("10天前是:"+showdate(-10)); 
window.alert("5天后是:"+showdate(5)); 
</script> 
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement map polygon drawing function How to use JS and Baidu Maps to implement map polygon drawing function Nov 21, 2023 am 10:53 AM

How to use JS and Baidu Maps to implement map polygon drawing function. In modern web development, map applications have become one of the common functions. Drawing polygons on the map can help us mark specific areas for users to view and analyze. This article will introduce how to use JS and Baidu Map API to implement map polygon drawing function, and provide specific code examples. First, we need to introduce Baidu Map API. You can use the following code to import the JavaScript of Baidu Map API in an HTML file

See all articles