moment.duration(10000).asMinutes() returns NaN

时间:2018-04-18 17:51:53

标签: node.js momentjs

I'm using momentjs (2.19.2) in my nodejs/typescript program. I import the lib using (tried both):

var moment = require('moment'); or import * as moment from 'moment';

When I write: moment().format("DD-MM-YYYY"), it returns 18-04-2018 which is correct.

Whereas: moment.duration(10000).asMinutes() returns NaN (same for other "as" methods)

It used to work correctly but now I can't figure out why these duration methods fail.

package.json

{
  "name": "MyApp",
  "version": "0.0.0",
  "description": "My first node js app",
  "author": {
    "email": "bla@bla.com",
    "name": "M. Blabla"
  },
  "engines": {
    "node": "8.9.x",
    "npm": "5.5.x"
  },
  "main": "./distr/app.js",
  "private": true,
  "scripts": {
    "i": "start --loglevel info",
    "develop": "gulp --gulpfile gulpfile.js develop",
    "test": "./node_modules/.bin/jasmine-node tests/specs",
  },
  "dependencies": {
    "body-parser": "~1.18.2",
    "compression": "^1.7.1",
    "cookie-parser": "~1.4.3",
    "debug": "~2.6.9",
    "express": "4.15.5",
    "gulp-nsp": "^2.4.2",
    "moment": "^2.19.2",
    "morgan": "~1.9.0",
    "node-libcurl": "1.2.0",
    "node-pre-gyp": "0.6.39",
    "nodemon": "1.12.1",
    "performance-now": "^2.1.0",
    "pm2": "^2.8.0",
    "response-time": "^2.3.2",
    "serve-favicon": "~2.4.5"
  },
  "devDependencies": {
    "@types/qs": "*",
    "@types/express": "^4.0.39",
    "@types/gulp": "^4.0.5",
    "@types/jasmine": "^2.8.3",
    "@types/node": "^8.0.50",
    "gulp": "^3.9.1",
    "gulp-total-task-time": "^0.1.0",
    "gulp-uglify": "^3.0.0",
    "jasmine-node": "^1.14.5",
    "nsp": "^3.1.0",
    "request": "^2.83.0",
    "request-promise-native": "^1.0.5",
    "tslint": "^5.8.0"
  }
}

launch.json

{
        "version": "0.2.0",
        "configurations": [
            {
                "type": "node",
                "request": "launch",
                "name": "Launch Program",
                "program": "${workspaceRoot}\\bin\\www",
                "env": {
                    "MODE_ENV": "developement",
                    "DEBUG": "express:*",
                },
                "outFiles": [
                    "${workspaceRoot}/**/*.js"
                ],
                "sourceMaps": true
            }
        ]
    }

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    "lib": ["es6","dom"],                 /* Specify library files to be included in the compilation:  */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
     "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    "outDir": "./distr",                        /* Redirect output structure to the directory. */
    //"rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
    "watch": true,
    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    "preserveConstEnums": true,
    "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    "paths": {
      "*":["*", "./src/*", "./typings-custom/*"]
      //"models/*":["./src/*"],
      //"libs/*":["./src/libs/*"]
    },                                        /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    "typeRoots" : ["./node_modules/@types", "./typings-custom/*"],
    //["./typings", "./typings-custom", "./node_modules/@types"],
    "types": ["node"] ,                         /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */

    /* Source Map Options */
    //"sourceRoot": "./src/"                   /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    //"mapRoot": "./distr"                       /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
  },
  //   "files": [
  //     //"./src/main.ts",
  //    //"./typings-custom/bla.d.ts",
  //    "./typings-custom/extensions.d.ts"
  // ],
  "include": [
     "./*.ts",
     //"./routes/*.ts",
     "./src/**/*.ts",
     "./src/libs/*.ts",
     "./typings-custom/*" //**/*.ts
  ],
  "exclude": [
    "node_modules",
    "**/*.spec.ts"
  ]
  // "compileOnSave": true
}

What do I do wrong with this duration or project configuration?

Thank you!

3 个答案:

答案 0 :(得分:0)

pass a unit to duration

moment.duration(10000, "s").asMinutes()

答案 1 :(得分:0)

我在使用moment.duration().asMinutes()功能时看不到任何问题。请查看以下代码段:

console.log(moment.duration(10000).asMinutes()); //working as expected

console.log(moment.duration(10000).minutes()); //working as expected
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>

注意:似乎问题出在其他地方。再次检查您的代码或共享JavaScript代码。

答案 2 :(得分:0)

好的,我终于设法摆脱了这个错误。

我删除了package-lock.json和node_modules文件夹,运行了npm i。 (这3个动作同时进行,所以我不知道哪一个是有用的)

现在,moment.duration返回一个值。

再次感谢你。