util.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /**
  2. * 将时间戳转换成日期格式
  3. * @param {long,时间戳} timestamp
  4. */
  5. function timeToYYYY_MM_DD_HH_mm_ss(timestamp) {
  6. if(("" + timestamp).length == 10){
  7. timestamp = timestamp * 1000;
  8. }
  9.     var date = new Date(timestamp);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
  10.     var Y = date.getFullYear() + '-';
  11.     var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
  12.     var D = date.getDate() < 10 ?  '0'+date.getDate()+ ' ' : date.getDate()+ ' ';
  13.     var h = date.getHours() < 10 ? '0'+date.getHours()+ ':' : date.getHours()+ ':';
  14.     var m = date.getMinutes() < 10 ? '0'+date.getMinutes()+ ':' : date.getMinutes()+ ':';
  15.     var s = date.getSeconds()< 10 ? '0'+date.getSeconds() : date.getSeconds();
  16.     return Y+M+D+h+m+s;
  17. }
  18. /**
  19. * ArrayBuffer转为字符串,参数为ArrayBuffer对象
  20. * @param {ArrayBuffer} buf
  21. */
  22. function ab16str(buf) {
  23. return String.fromCharCode.apply(null, new Uint16Array(buf));
  24. }
  25. /**
  26. * 字符串转为ArrayBuffer对象,参数为字符串
  27. * @param {string} str
  28. */
  29. function str16ab(str) {
  30. var buf = new ArrayBuffer(str.length * 2); // 每个字符占用2个字节
  31. var bufView = new Uint16Array(buf);
  32. for (var i = 0, strLen = str.length; i < strLen; i++) {
  33. bufView[i] = str.charCodeAt(i);
  34. }
  35. return buf;
  36. }
  37. /**
  38. * 字符编码数值对应的存储长度:
  39. * UCS-2编码(16进制) UTF-8 字节流(二进制)
  40. * 0000 - 007F 0xxxxxxx (1字节)
  41. * 0080 - 07FF 110xxxxx 10xxxxxx (2字节)
  42. * 0800 - FFFF 1110xxxx 10xxxxxx 10xxxxxx (3字节)
  43. */
  44. String.prototype.getBytesLength = function() {
  45. var totalLength = 0;
  46. var charCode;
  47. for (var i = 0; i < this.length; i++) {
  48. charCode = this.charCodeAt(i);
  49. if (charCode < 0x007f) {
  50. totalLength++;
  51. } else if ((0x0080 <= charCode) && (charCode <= 0x07ff)) {
  52. totalLength += 2;
  53. } else if ((0x0800 <= charCode) && (charCode <= 0xffff)) {
  54. totalLength += 3;
  55. } else{
  56. totalLength += 4;
  57. }
  58. }
  59. return totalLength;
  60. }