locked
convert today, tomorrow, yesterday, last week, last month and so on to date moment.js angularjs RRS feed

  • Question

  • User2108892867 posted

    Hello everyone, I have a textbox that I allow user to specify the default date. They could write the word: Today, tomorrow, yesterday and next month and so on. I would like to pick up those word and convert it into date relative to today's date. Is there a good way to do this using moment.js?

    Thanks. 

    Tuesday, August 28, 2018 3:00 AM

All replies

  • User753101303 posted

    Hi,

    Or maybe parse <number> <text> which could be used then by  https://momentjs.com/docs/#/manipulating/add/ ie 1 day 2 months would call:

    moment().add(1,"days").add(2,"months")

    Over time you could handle special cases ("tomorrow", "yesterday", "next" being 1) etc...

    Make sure though it will be more convenient and disoverable for users compared with using a more classic calendar ui (for example depending on the app, they want to see which weekday it is ?)

    Tuesday, August 28, 2018 4:13 PM
  • User2108892867 posted

    Thanks. Yes I am trying to see if moment.js actually has something out of the box. For now perhaps that's the best way to deal with this by hard coded the word like so

    moment().add(1,"days").add(2,"months")

    Wednesday, August 29, 2018 10:08 PM
  • User283571144 posted

    Hi asplearning,

    Thanks. Yes I am trying to see if moment.js actually has something out of the box. For now perhaps that's the best way to deal with this by hard coded the word like so

    moment().add(1,"days").add(2,"months")

    As far as I know, there is no built in method to map tomorrow, next week to moment values.

    I suggest you could create your own fromString function and adding it to moment.fn.

    More details, you could refer to below codes:

    moment.fn.fromString = function(param){
      if( param === 'tomorrow' ){
        return this.clone().add(1, 'day');
      } else if( param === 'next week' ){
        return this.clone().add(1, 'week');
      } else if( param === 'yesterday' ){
        return this.clone().subtract(1, 'day');
      }
      
      return this;
    }
    
    
    console.log( moment().fromString('tomorrow').format() )
    console.log( moment().fromString('next week').format() )
    console.log( moment().fromString('yesterday').format() )

    Best Regards,

    Brando

    Tuesday, September 4, 2018 6:51 AM