最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - String value with moment.js - Stack Overflow

programmeradmin1浏览0评论

My JS:

...
var dateText='';
dateText = moment(scope.mtxMaxdate,'MM-DD-YYYY');
console.log(dateText);
...

I want to output my value example: '12/12/2014' but in the console i have:

Moment {_isAMomentObject: true, _i: "17/12/2014", _f: "MM-DD-YYYY", _isUTC: false, _pf: Object…}

why..?

My JS:

...
var dateText='';
dateText = moment(scope.mtxMaxdate,'MM-DD-YYYY');
console.log(dateText);
...

I want to output my value example: '12/12/2014' but in the console i have:

Moment {_isAMomentObject: true, _i: "17/12/2014", _f: "MM-DD-YYYY", _isUTC: false, _pf: Object…}

why..?

Share Improve this question asked Dec 16, 2014 at 10:43 MercerMercer 9,99632 gold badges115 silver badges174 bronze badges 2
  • Why do you expect that dateText will be a string. moment: String + Format creates a moment date object out of a string using the given format. – t.niese Commented Dec 16, 2014 at 10:46
  • As _i shows your scope.mtxMaxdate is 17/12/2014 but you tell moment that the date you pass has to be in the format MM-DD-YYYY, so your date is invalid. – t.niese Commented Dec 16, 2014 at 10:52
Add a ment  | 

2 Answers 2

Reset to default 5

As stated in momentjs docs you should use .format() function.

Something like this should do it :

var dateText='12-12-2014';
var dateObject = moment(dateText,'MM-DD-YYYY');
console.log(dateObject.format('DD/MM/YYYY'));

The format you give as an argument on second line is just the parse format.

I updated code, the fact that you use angular or not doesn't change a thing. I think what you do not understand is that moment js generates an object from a string date. You can then format this date object just as you want.

Made a jsfiddle in case you don't get it.

But doing as per the accepted answer, there is a warning of Deprecation that is thrown. Deprecation warning in moment js

However this doesn't seem to throw a warning now. Not sure if the resultant value is how you may need it to be.

> moment("12-25-1995", ["MM-DD-YYYY", "YYYY-MM-DD"]).format('MM-DD-YYYY')
> "12-25-1995"

If you have Date object convert it toString() and then apply the .format()

发布评论

评论列表(0)

  1. 暂无评论