Remove Seconds/ Milliseconds from Date convert to ISO String

前端 未结 9 1801
滥情空心
滥情空心 2020-12-15 15:41

I have a date object that I want to

  1. remove the miliseconds/or set to 0
  2. remove the seconds/or set to 0
  3. Convert to ISO string

F

相关标签:
9条回答
  • 2020-12-15 15:46

    A non-library regex to do this:

    new Date().toISOString().replace(/.\d+Z$/g, "Z");
    

    This would simply trim down the unnecessary part. Rounding isn't expected with this.

    0 讨论(0)
  • 2020-12-15 15:49

    A bit late here but now you can:

    var date = new Date();

    this obj has:

    date.setMilliseconds(0);

    and

    date.setSeconds(0);

    then call toISOString() as you do and you will be fine.

    No moment or others deps.

    0 讨论(0)
  • 2020-12-15 15:55
    let date = new Date();
    date = new Date(date.getFullYear(), date.getMonth(), date.getDate());
    

    I hope this works!!

    0 讨论(0)
  • 2020-12-15 16:01

    You can use the startOf() method within moment.js to achieve what you want.

    Here's an example:

    var date = new Date();
    
    var stringDateFull = moment(date).toISOString();
    var stringDateMinuteStart = moment(date).startOf("minute").toISOString();
    
    $("#fullDate").text(stringDateFull);
    $("#startOfMinute").text(stringDateMinuteStart);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.js"></script>
    <p>Full date: <span id="fullDate"></span></p>
    <p>Date with cleared out seconds: <span id="startOfMinute"></span></p>

    0 讨论(0)
  • 2020-12-15 16:01

    We can do it using plain JS aswell but working with libraries will help you if you are working with more functionalities/checks.

    You can use the moment npm module and remove the milliseconds using the split Fn.

    const moment = require('moment')
    
    const currentDate = `${moment().toISOString().split('.')[0]}Z`;
    
    console.log(currentDate) 
    
    

    Refer working example here: https://repl.it/repls/UnfinishedNormalBlock

    0 讨论(0)
  • 2020-12-15 16:02

    While this is easily solvable with plain JavaScript (see RobG's answer), I wanted to show you the Moment.js solution since you tagged your questions as "momentjs":

    moment().seconds(0).milliseconds(0).toISOString();
    

    This gives you the current datetime, without seconds or milliseconds.

    Working example: http://jsbin.com/bemalapuyi/edit?html,js,output

    From the docs: http://momentjs.com/docs/#/get-set/

    0 讨论(0)
提交回复
热议问题