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

查看:25
本文介绍了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 格式序列化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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