简体   繁体   中英

How do I insert a string at more than one position in a string?

I have this two strings in Javascript 20130927 this represent a date and 192600 which is a hour. I want to use Moment.js library to parse them as a valid Date/Time element but before I need to convert to valid date javascript object so I need to transform the string in something like 2013-09-27 or 2013/09/27 (I though both are valid) and 19:26:00 . I read about slice() and substr() methods but don't get how to use them to achieve the expected result. Any help?

You can use substring like this:

str = "20130927"
year = str.substring(0,4)
month = str.substring(4,6)
day = str.substring(6,8)

And then create a new Date object with that like this:

new Date(year, month, day)

For the time you would do something similar and pass the results as additional parameters to the Date constructor.

You should be able to use moment's built in parser.

Something along these lines works for me:

var moment = require('moment');
var date = "20130927";
var hour = "192600";
var newDateTime = moment(date+hour, "YYYYMMDDHHmmss");
console.log(newDateTime)

outputs:

{ _i: '20130927192600',
  _f: 'YYYYMMDDHHmmss',
  _l: undefined,
  _isUTC: false,
  _a: [ 2013, 8, 27, 19, 26, 0, 0 ],
  _d: Fri Sep 27 2013 19:26:00 GMT-0400 (EDT) }

See here for additional info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM