I have a moment value passed to a function and I try to format the moment to a string in the format YYYY-MM-DD HH:mm (SS-ISO 8601). The date is accurately formatted but the time value is omitted.
Code:
timeTransformer(value: moment.Moment) {
return value == null ? null : value.format('YYYY-MM-DD HH:mm'); //Time is 00:00 even though I can see that moment has values 15:37:19
}
I have a moment value passed to a function and I try to format the moment to a string in the format YYYY-MM-DD HH:mm (SS-ISO 8601). The date is accurately formatted but the time value is omitted.
Code:
timeTransformer(value: moment.Moment) {
return value == null ? null : value.format('YYYY-MM-DD HH:mm'); //Time is 00:00 even though I can see that moment has values 15:37:19
}
Share
Improve this question
edited Oct 31, 2017 at 10:33
Marcus
asked Oct 31, 2017 at 10:21
MarcusMarcus
8,66911 gold badges66 silver badges92 bronze badges
14
-
Do not use Internal properties like
_i
and_d
. – VincenzoC Commented Oct 31, 2017 at 10:23 -
I don´t, what do you mean? I use
value.format
wherevalue
is the moment value. The reason _i and _d are visible is because I wanted to show that the moment has time properties set. The image is from theWatch
window in the Chrome console. – Marcus Commented Oct 31, 2017 at 10:26 -
2
I wanted to sugggest to do not look at the value of
_
internal properties. If you think that something is wrong with parsing and showing value of a moment object, please share relevant code. Where doesvalue
e from? – VincenzoC Commented Oct 31, 2017 at 10:29 -
1
Again, do not look at
_i
value, but please share the code you are using to createvalue
var. – VincenzoC Commented Oct 31, 2017 at 10:38 - 1 @Marcus It'll be to do with when it's dealing with timezones etc - even when dealing with just the date part, it needs to know times as depending on the timezone, even the date might change. – James Thorpe Commented Oct 31, 2017 at 11:17
1 Answer
Reset to default 5As per the documentation:
As such, the values of
_d
and any other properties prefixed with_
should not be used for any purpose.
Having said that, we can explain what's going on. In your case, we can see both _i
and _f
are set. _i
would appear to be used to store the initial value you passed to moment. _f
looks to store the format you told moment to parse the input with. See here:
var m = moment('2017/10/04 12:34:56', 'YYYY/MM/DD');
console.log(m._i);
console.log(m._f);
console.log(m.format('YYYY-MM-DD HH:mm'))
<script src="https://cdnjs.cloudflare./ajax/libs/moment.js/2.19.1/moment.min.js"></script>
The _i
property is set in the same way, but logging .format('YYYY-MM-DD HH:mm')
shows the same 00:00
you see. This is because I told moment to parse it as YYYY/MM/DD
- you used YYYY-MM-DD
.
To get the time working, you need to go and alter the code that is creating your moment object.