function GUID() {
this.date = new Date(); //先new一個時間備用
GUID.prototype.newGUID = function () {
this.date = new Date();
var guidStr = '';
sexadecimalDate = this.hexadecimal(this.getGUIDDate(), 16);
sexadecimalTime = this.hexadecimal(this.getGUIDTime(), 16);
for (var i = 0; i < 9; i++) {
guidStr += Math.floor(Math.random() * 16).toString(16);
}
guidStr += sexadecimalDate;
guidStr += sexadecimalTime;
while (guidStr.length < 32) {
guidStr += Math.floor(Math.random() * 16).toString(16);
}
return this.formatGUID(guidStr);
}
獲取當前日期的GUID格式,即8位數的日期:
GUID.prototype.getGUIDDate = function () {
return this.date.getFullYear() + this.addZero(this.date.getMonth() + 1) + this.addZero(this.date.getDay());
}
獲取當前時間的GUID格式,即8位數的時間,包括毫秒,毫秒為2位數:12300933
返回GUID日期格式的字條串
GUID.prototype.getGUIDTime = function () {
return this.addZero(this.date.getHours()) + this.addZero(this.date.getMinutes()) + this.addZero(this.date.getSeconds()) + this.addZero(parseInt(this.date.getMilliseconds() / 10));
}
為一位數的正整數前面添加0,如果是可以轉成非NaN數字的字符串也可以實現
參數表示准備再前面添加0的數字或可以轉換成數字的字符串
如果符合條件,返回添加0后的字條串類型,否則返回自身的字符串
GUID.prototype.addZero = function (num) {
if (Number(num).toString() != 'NaN' && num >= 0 && num < 10) {
return '0' + Math.floor(num);
} else {
return num.toString();
}
}
將y進制的數值,轉換為x進制的數值
1個參數表示欲轉換的數值;第2個參數表示欲轉換的進制;第3個參數可選,表示當前的進制數,如不寫則為10
返回轉換后的字符串
GUID.prototype.hexadecimal = function (num, x, y) {
if (y != undefined) {
return parseInt(num.toString(), y).toString(x);
} else {
return parseInt(num.toString()).toString(x);
}
}
格式化32位的字符串為GUID模式的字符串
第1個參數表示32位的字符串
標准GUID格式的字符串
GUID.prototype.formatGUID = function (guidStr) {
var str1 = guidStr.slice(0, 8) + '-',
str2 = guidStr.slice(8, 12) + '-',
str3 = guidStr.slice(12, 16) + '-',
str4 = guidStr.slice(16, 20) + '-',
str5 = guidStr.slice(20);
return str1 + str2 + str3 + str4 + str5;
}