jquery 時間戳與字符串日期的相互轉換


1、在<script>標簽下聲明function:

 1 (function($) {
 2     $.extend({
 3         myTime: {
 4             /**
 5              * 當前時間戳
 6              * @return <int>        unix時間戳(秒)  
 7              */
 8             CurTime: function(){
 9                 return Date.parse(new Date())/1000;
10             },
11             /**              
12              * 日期 轉換為 Unix時間戳
13              * @param <string> 2014-01-01 20:20:20  日期格式              
14              * @return <int>        unix時間戳(秒)              
15              */
16             DateToUnix: function(string) {
17                 var f = string.split(' ', 2);
18                 var d = (f[0] ? f[0] : '').split('-', 3);
19                 var t = (f[1] ? f[1] : '').split(':', 3);
20                 return (new Date(
21                         parseInt(d[0], 10) || null,
22                         (parseInt(d[1], 10) || 1) - 1,
23                         parseInt(d[2], 10) || null,
24                         parseInt(t[0], 10) || null,
25                         parseInt(t[1], 10) || null,
26                         parseInt(t[2], 10) || null
27                         )).getTime() / 1000;
28             },
29             /**              
30              * 時間戳轉換日期              
31              * @param <int> unixTime    待時間戳(秒)              
32              * @param <bool> isFull    返回完整時間(Y-m-d 或者 Y-m-d H:i:s)              
33              * @param <int>  timeZone   時區              
34              */
35             UnixToDate: function(unixTime, isFull, timeZone) {
36                 if (typeof (timeZone) == 'number')
37                 {
38                     unixTime = parseInt(unixTime) + parseInt(timeZone) * 60 * 60;
39                 }
40                 var time = new Date(unixTime * 1000);
41                 var ymdhis = "";
42                 ymdhis += time.getUTCFullYear() + "-";
43                 ymdhis += (time.getUTCMonth()+1) + "-";
44                 ymdhis += time.getUTCDate();
45                 if (isFull === true)
46                 {
47                     ymdhis += " " + time.getUTCHours() + ":";
48                     ymdhis += time.getUTCMinutes() + ":";
49                     ymdhis += time.getUTCSeconds();
50                 }
51                 return ymdhis;
52             }
53         }
54     });
55 })(jQuery);

2、返回值:

1 var date = $.myTime.DateToUnix('2014-5-15 20:20:20');
2 var date = $.myTime.UnixToDate(1325347200);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM