如何在angular 4中将字符串转换为Date类类型

roo*_*eja 5 typescript angular

我的 .ts 文件中有如下字符串。

const date = "5/03/2018";
Run Code Online (Sandbox Code Playgroud)

我想转换为日期类型,它是 angular Date 类返回的默认日期类型。

 Tue Apr 03 2018 20:20:12 GMT+0530 (India Standard Time)
Run Code Online (Sandbox Code Playgroud)

现在我必须将此字符串类型日期转换为默认角度日期类型。有帮助吗?我尝试了以下方法。

const date1 = new Date("5/03/2018");
Run Code Online (Sandbox Code Playgroud)

但它不起作用我没有得到所需的格式。这是 stackblitz 链接,任何建议都会有所帮助。 https://stackblitz.com/edit/angular-gdwku3

mic*_*toh 6

将日期格式更改为YYYY-MM-DD格式创建日期对象。

var date = new Date ("2014-10-10"); console.log(date.toDateString());

记得调用toDateString方法。


FRE*_*CIA 5

看看这个函数(stackblitz),它会格式化不同格式的日期,你可以随意使用年、月和日的位置:

  parse(value: any): Date | null {
    if ((typeof value === 'string') && (value.includes('/'))) {
      const str = value.split('/');

      const year = Number(str[2]);
      const month = Number(str[1]) - 1;
      const date = Number(str[0]);

      return new Date(year, month, date);
    } else if((typeof value === 'string') && value === '') {
      return new Date();
    }
    const timestamp = typeof value === 'number' ? value : Date.parse(value);
    return isNaN(timestamp) ? null : new Date(timestamp);
  }
Run Code Online (Sandbox Code Playgroud)