2

I am working in React. I am troubled with getting right time format. I am selecting a time from drop down and used moment(inputTime,HH:mm) to format time, but this is how I get. What is the reason for it? Is there any alternative way other than moment(inputTime).format("HH:mm")?

Moment {_isAMomentObject: true, _i: "Tue May 04 2021 03:53:21 GMT+0530 (India Standard Time)", _isUTC: false, _pf: {…}, _locale: Locale, …} _d: Tue May 04 2021 03:53:21 GMT+0530 (India Standard Time) {} _i: "Tue May 04 2021 03:53:21 GMT+0530 (India Standard Time)" _isAMomentObject: true _isUTC: false _isValid: true _locale: Locale {_calendar: {…}, _longDateFormat: {…}, _invalidDate: "Invalid date", _dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal: ƒ, …} _pf: {empty: false, unusedTokens: Array(0), unusedInput: Array(0), overflow: -2, charsLeftOver: 0, …} __proto__: Object 
4
  • 1
    What's wrong with .format("HH:mm")? Commented May 4, 2021 at 18:42
  • @HereticMonkey I will get an error "'isBetween' does not exist on type 'string'. when we perform the following code . inputTime.format("HH:mm").isBetween(beforeTime, afterTime); Commented May 4, 2021 at 19:05
  • The you don't need the formatted moment for that. Add the .format("HH:mm") only to where you show it in the view. Commented May 4, 2021 at 19:14
  • To put it another way. A moment object (what you have shown logged) wraps a Date object, which is the time value you parsed, arbitrarily set to today's date and put into the time zone of the browser. That moment object has functions like isBetween attached to it. It does not display the time formatted as you parsed it (technically, if you dig deep into that _pf property, you could probably find it, but that's implementation detail you should not depend on). When you call format, it takes the Date and time zone information and provides the time, formatted as desired. Commented May 4, 2021 at 19:32

1 Answer 1

1

By using moment(inputTime,HH:mm), you are creating a moment object. Which is why you get Moment {_isAMomentObject: true, ...} when printing this object to the console.

If you want to have it in the format "HH:mm", it means that you want to have a string representation of your moment object in the format sus-cited. To do so, one of the correct way is to use the format method on the moment object.

var input_time = "10:46"; var date_a = moment(input_time, "HH:mm"); console.log(date_a); >> Moment {...} // moment object var date_a_str = date_a.format("HH:mm"); console.log(date_a_str); >> "10:46" // string 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.