js 简单的获取当前时间 已经格式转换 时间比较

小鱼儿 2022-06-17 01:53 408阅读 0赞
  1. //替换字符串
  2. function Replace(str, from, to) {
  3. return str.split(from).join(to);
  4. }
  5. // 日期类型格式成指定的字符串
  6. function FormatDate(date, format) {
  7. format = Replace(format, "yyyy", date.getFullYear());
  8. format = Replace(format, "MM", GetFullMonth(date));
  9. format = Replace(format, "dd", GetFullDate(date));
  10. format = Replace(format, "HH", GetFullHour(date));
  11. format = Replace(format, "mm", GetMinutes(date));
  12. format = Replace(format, "ss", GetSeconds(date));
  13. return format;
  14. }
  15. //js日期字符串转换成日期类型
  16. function parseDate(dateStr) {
  17. return new Date(Replace(dateStr, "-", "/"));
  18. }
  19. //增加月
  20. function AddMonths(date, value) {
  21. date.setMonth(date.getMonth() + value);
  22. return date;
  23. }
  24. //增加天
  25. function AddDays(date, value) {
  26. date.setDate(date.getDate() + value);
  27. date = FormatDate(date,'yyyy-MM-dd HH:mm:ss');
  28. return date;
  29. }
  30. //增加时
  31. function AddHours(date, value) {
  32. date.setHours(date.getHours() + value);
  33. return date;
  34. }
  35. //返回月份(两位数)
  36. function GetFullMonth(date) {
  37. var v = date.getMonth() + 1;
  38. if (v > 9) return v.toString();
  39. return "0" + v;
  40. }
  41. //返回日(两位数)
  42. function GetFullDate(date) {
  43. var v = date.getDate();
  44. if (v > 9) return v.toString();
  45. return "0" + v;
  46. }
  47. //返回时(两位数)
  48. function GetFullHour(date) {
  49. var v = date.getHours();
  50. if (v > 9) return v.toString();
  51. return "0" + v;
  52. }
  53. //分
  54. function GetMinutes(date){
  55. var v = date.getMinutes();
  56. if (v > 9) return v.toString();
  57. return "0" + v;
  58. }
  59. //秒
  60. function GetSeconds(date){
  61. var v = date.getSeconds();
  62. if (v > 9) return v.toString();
  63. return "0" + v;
  64. }
  65. //比较两个时间
  66. function compareDate() {
  67. var mydate = AddDays(parseDate("2012-08-23"), 1);
  68. var nowdate = new Date();
  69. if (nowdate.getTime() < mydate.getTime()) {
  70. return FormatDate(nowdate, "yyyy-MM-dd");
  71. }
  72. return FormatDate(mydate, "yyyy-MM-dd");
  73. }

发表评论

表情:
评论列表 (有 0 条评论,408人围观)

还没有评论,来说两句吧...

相关阅读