js日期传递函数

问题描述 投票:0回答:1

我在javascript日期中遇到一个问题,我想在我的GetFormattedDate函数中加入这行。

我试过了,但我不能在我的函数中实现这个逻辑。

var currentdate = new Date();
var myTime1 = currentdate.getHours() +':'+ (currentdate.getMinutes() <= 29 ? '00' : '30') ;  //output 18:43

我的代码。

  function GetFormattedDate(date) {   
      var month = ("0" + (date.getMonth() + 1)).slice(-2);
      var day  = ("0" + (date.getDate())).slice(-2);
      var year = date.getFullYear();
      var hour =  ("0" + (date.getHours())).slice(-2);
      var min =  ("0" + (date.getMinutes())).slice(-2);
      var seg = ("0" + (date.getSeconds())).slice(-2);

      return year + "-" + month + "-" + day + " " + hour + ":" +  min + ":" + seg + " " ;
}

我的代码:

`2020-05-12 01:00:00` //if minutes are 0 to 29 then show current hours reset the minutes again start with 0 like 18:00:00 and seconds become 0

`2020-05-12 01:30:00 ` //if minutes are 29 to 59 then show current hours reset the minutes again start with 30 like 18:30:00 and seconds become 0
javascript function date datetime
1个回答
0
投票

当你设置了 minseg 变量

替换这两行

      var min =  ("0" + (date.getMinutes())).slice(-2);
      var seg = ("0" + (date.getSeconds())).slice(-2);

      var min =  date.getMinutes() <= 29 ? '00' : '30';
      var seg = '00';

function GetFormattedDate(date) {
  var month = ("0" + (date.getMonth() + 1)).slice(-2);
  var day = ("0" + (date.getDate())).slice(-2);
  var year = date.getFullYear();
  var hour = ("0" + (date.getHours())).slice(-2);
  var min = date.getMinutes() <= 29 ? '00' : '30';
  var seg = '00';

  return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + seg + " ";
}

console.log(GetFormattedDate(new Date));

0
投票

你在向函数传递一个字符串。根据你在评论中提供的链接,你需要将日期的字符串表示解析成一个实际的日期对象。var d = Date.parse("March 21, 2012"); 在这里阅读更多内容。https:/www.w3schools.comjsrefjsref_parse.asp

一旦你有了新的 Date 对象,设置其秒数。

var d = new Date();
d.setSeconds(d.getSeconds() <= 29 ? 0 : 30);

现在你可以通过 d 到你的功能。

GetFormattedDate(d);
© www.soinside.com 2019 - 2024. All rights reserved.