Angular如何在JSON请求中以yyyy-MM-dd格式序列化Date [英] Angular How to serialize Date in format yyyy-MM-dd in json request

查看:259
本文介绍了Angular如何在JSON请求中以yyyy-MM-dd格式序列化Date的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,该对象的日期类型为'birthDate'. 在屏幕上,我应该以DD/MM/YYYY格式显示生日.现在,我使用引导程序bsDatePicker. 但是在数据库中,它以YYYY-MM-DD(类型字符串)的格式存储.因此,要提交修改,我应该将生日转换为这种格式.

I have an object who has a property 'birthDate' of type Date. On screen, I should display the birthday in format DD/MM/YYYY. Now I use bootstrap bsDatePicker. But in the database, it is stored in the format YYYY-MM-DD(type string). So to submit the modification, I should convert the birthday to this format.

您能告诉我如何在JSON请求中将Date(DD/MM/YYYY)序列化为YYYY-MM-DD格式吗?

Can you tell me how to serialize the Date(DD/MM/YYYY) to the format YYYY-MM-DD in the JSON request?

您有什么好主意来优化转换,而无需对数据库进行任何更改?

Do you have any good idea to optimize the conversion without any change in the database?

谢谢

推荐答案

首先,您将创建一个接受包含日期的字符串的函数.然后将其转换.在该函数的末尾,我有一些三元代码,因为如果您不添加该部分,则日期可能是 2018-4-2 ,而您希望它是 2018-04-02

First you are going to create a function that accepts a string that contains the date. Then convert it. At the end of the function I have some ternary code because if you don't add that part, the date could be 2018-4-2 and you want it 2018-04-02

dateFormater(date:string):string{    
   const today = new Date(date);        
   const day = today.getDate()+1; 
   const month = today.getMonth()+1;
   const year = today.getFullYear();

   return year + "-" + (month<10 ? ("0" + month) : month)+ "-" + (day<10 ? ("0" + day) : day);    
 }

这篇关于Angular如何在JSON请求中以yyyy-MM-dd格式序列化Date的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆