开发者

js date object based on strings

I want to make a js date object based on strings in format YYYYMMDD and HHMMSS.

function makeTimeStamp(myDate, MyTime){
    // myDate format YYYYMMDD
    // myTime format HHMMSS
    var YYYY = myDate.substring(0, 3);
    var MM = myDate.substring(4, 5);
    var DD = myDate.substring(6,7);

    var HH = myTime.开发者_StackOverflowsubstring(0,1);
    var MM = myTime.substring(2,3);
    var SS = myTime.substring(4,5);
        jsDate = 
}


If you meant to be creating a Date object for given year, month, day, hours, minutes and seconds, you can use new Date(year, month - 1, day, hours, minutes, seconds) to create a Date instance for it. Note that the month is 0 based, January is 0, February 1, etc. Hence the MM - 1;

function stringToDate(myDate, myTime){
    // myDate format YYYYMMDD
    // myTime format HHMMSS
    var YYYY = myDate.substr(0, 4);
    var MM = myDate.substr(4, 2);
    var DD = myDate.substr(6, 2);

    var HH = myTime.substr(0, 2);
    var mm = myTime.substr(2, 2);
    var SS = myTime.substr(4, 2);

    var jsDate = new Date(YYYY, MM - 1, DD, HH, mm, SS);
    return jsDate;
}

// returns a Date object for given date and time
var jsDate = stringToDate("20110818", "191500");
// returns 1313687700000
var timestamp = jsDate.getTime();

Note that I'm using string.substr(start_position, length) as you can easily see the length of the returned value.


You can try Date.js which is a date library. http://www.datejs.com/


You can convert those date and time formats in to ISO format pretty easily (e.g. "2011-08-18T12:34:56") and use a regular expression to make sure the arguments are formatted properly:

function makeTimestamp(myDate, myTime) {
  var ds = myDate.match(/^(\d{4})(\d\d)(\d\d)$/)
    , ts = myTime.match(/^(\d\d)(\d\d)(\d\d)$/);
  if (!ds || !ts) { return null; }
  return new Date(ds.slice(1,4).join("-") + "T" + ts.slice(1,4).join(":"));
}

var d = makeTimestamp('20110818', '123456');
d // => Fri Aug 19 2011 12:34:56 GMT-0400 (EDT)


you can try this: https://www.npmjs.com/package/timesolver

npm i timesolver

use it in your code:

const timeSolver = require('timeSolver'); const date = new Date(); const dateString = timeSolver.getString(date, 'YYYYMMDD HHMMSS'); `

You can get date string by using this method:

const dateString = timeSolver.getString(date, format);

Hope this will help you!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜