javascript 格式输入从 M/D/YYYY 到 YYYYMMDD
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28477304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Format input from M/D/YYYY to YYYYMMDD
提问by MC James
Write a function that converts user entered date formatted as M/D/YYYYto a format required by an API (YYYYMMDD). The parameter "userDate
" and the return value are strings.
编写一个函数,将用户输入的格式为M/D/YYYY 的日期转换为API 所需的格式 ( YYYYMMDD)。参数“ userDate
”和返回值是字符串。
For example, it should convert user entered date "12/31/2014" to "20141231"suitable for the API.
例如,它应该将用户输入的日期“12/31/2014”转换为适合 API 的“20141231”。
function formatDate(userDate)
{
userDate = new Date();
y = userDate.getFullYear();
m = userDate.getMonth();
d = userDate.getDate();
return y + m + d;
}
is there anything wrong with my code?
我的代码有什么问题吗?
couldn't pass an online test.
无法通过在线测试。
回答by Guffa
There are five problems with the code.
代码有五个问题。
- It ignores the input parameter and uses the current time instead (
Date()
). - It assumes that the computer where it runs uses the m/d/y date format to parse the string (if it actually would have parsed the string).
- The
getMonth
method returns the month index, not the month number, so you have to add one to it. - It uses addition to put the values together instead of string concatenation.
- It doesn't format the month and date into two digits.
- 它忽略输入参数并使用当前时间代替 (
Date()
)。 - 它假定运行它的计算机使用 m/d/y 日期格式来解析字符串(如果它实际上会解析字符串)。
- 该
getMonth
方法返回月份索引,而不是月份编号,因此您必须向其添加一个。 - 它使用加法将值放在一起而不是字符串连接。
- 它不会将月份和日期格式化为两位数。
Ignoring the date format issue, the others can be fixed using:
忽略日期格式问题,可以使用以下方法修复其他问题:
function formatDate(userDate) {
userDate = new Date(userDate);
y = userDate.getFullYear().toString();
m = (userDate.getMonth() + 1).toString();
d = userDate.getDate().toString();
if (m.length == 1) m = '0' + m;
if (d.length == 1) d = '0' + d;
return y + m + d;
}
Instead of parsing the string to a date, and the format it to a string again, you can just rearrange the characters in the string. This circumvents the date format issue:
无需将字符串解析为日期,然后再次将其格式化为字符串,您只需重新排列字符串中的字符即可。这绕过了日期格式问题:
function formatDate(userDate) {
var parts = userDate.split('/');
if (parts[0].length == 1) parts[0] = '0' + parts[0];
if (parts[1].length == 1) parts[1] = '0' + parts[1];
return parts[2] + parts[0] + parts[1];
}
回答by NatalieSalemme
function formatDate(userDate) {
// format from M/D/YYYY to YYYYMMDD
let array = userDate.split("/");
while(array[0].length < 2) {
array[0] = "0" + array[0];
}
while(array[1].length < 2) {
array[1] = "0" + array[1];
}
let arrayAnswer = array[2]+ array[0]+ array[1];
return arrayAnswer;
}
console.log(formatDate("1/3/2014"));
//output must equal 20140103
As a beginner, this was the simplest way I was able to do this one. It made more sense to me to split it up, add the 0's and then sort it into the correct places.
作为初学者,这是我能够做到的最简单的方法。对我来说更有意义的是将其拆分,添加 0,然后将其分类到正确的位置。
回答by gvee
Follow through the comments in code - step by step showing one wayof solving your problem.
按照代码中的注释进行操作 - 逐步显示解决问题的一种方法。
// Function shell. Accepts a parameter userDate, returns a value
function formatDate(userDate) {
// Step 1: attempt to convert parameter to a date!
var returnDate = new Date(userDate);
// Step 2: now that this is a date, we can grab the day, month and year
// portions with ease!
var y = returnDate.getFullYear();
var m = returnDate.getMonth() + 1; // Step 6
var d = returnDate.getDay();
// Step 3: The bit we did above returned integer values. Because we are
// *formatting*, we should really use strings
y = y.toString();
m = m.toString();
d = d.toString();
// Step 4: The value of our month and day variables can be either 1 or 2
// digits long. We need to force them to always be 2 digits.
// There are lots of ways to achieve this. Here's just one option:
if (m.length == 1) {
m = '0' + m;
}
if (d.length == 1) {
d = '0' + d;
}
// Step 5: combine our new string values back together!
returnDate = y + m + d;
// Step 6: did you notice a problem with the output value?
// The month is wrong! This is because getMonth() returns a value
// between 0 and 11 i.e. it is offset by 1 each time!
// Look back up at Step 2 and see the extra piece of code
// Step 7: Looks pretty good, huh? Well, it might pass you your quiz
// question, but it's still not perfect.
// Do you know why?
// Well, it assumes that the parameter value is
// a) always an actual date (e.g. not "dave")
// b) our Step1 correctly converts the value (e.g. the client, where
// the JS is run, uses the date format m/d/y).
// I am in the UK, which doesn't like m/d/y, so my results will
// be different to yours!
// I'm not going to solve this here, but is more food for thought for you.
// Consider it extra credit!
return returnDate;
}
// Display result on page -->
document.getElementById("result").innerText += formatDate("1/1/2015");
<div id="result">Result: </div>
回答by Legionar
You are using +
with integers, you have to cast them as string.
您正在使用+
整数,您必须将它们转换为字符串。
function formatDate(userDate) {
userDate = new Date(userDate);
y = userDate.getFullYear();
m = userDate.getMonth() + 1;
d = userDate.getDate();
return y.toString() +
('0' + m.toString()).slice(-2) +
('0' + d.toString()).slice(-2);
}
And also you need to add leading zero to month and day.
而且您还需要将前导零添加到月份和日期。
Example:
例子:
console.log(formatDate('2/12/2015'));
console.log(formatDate('2/12/2015'));
will write to log 20150212
将写入日志 20150212
console.log(formatDate('1/1/2015'));
console.log(formatDate('1/1/2015'));
will write to log 20150101
将写入日志 20150101
回答by leap
function formatDate(userDate) {
// format from M/D/YYYY to YYYYMMDD
var oldDate = String(userDate).split('/');
if (oldDate[0].length==1)oldDate[0]='0'+oldDate[0];
if (oldDate[1].length==1)oldDate[1]='0'+oldDate[1];
var newDate = [oldDate[2], oldDate[0], oldDate[1]];
return newDate.join('');
}
console.log(formatDate("12/31/2014"));
回答by Farid Ansari
function formatDate(userDate) {
userDate = new Date(userDate);
year= userDate.getFullYear().toString();
month = (userDate.getMonth() + 1).toString();
date = userDate.getDate().toString();
return year + (month=(month.length==1)?'0'+month:month) + (date=(date.length==1)?'0'+date:date);
}
console.log(formatDate("12/10/2017"));
Some more details:
更多细节:
(1)userDate = new Date(userDate) => create an instance of Date object.
(1)userDate = new Date(userDate) => 创建一个Date对象的实例。
(2)userDate.getFullYear() is get year from userDate. Similarly user.getMonth() for month and userDate.getDate() for date...I've added +1 to month because month return is starts 0, i.e for month 6 it return 5 so 1 is added.
(2)userDate.getFullYear() 是从 userDate 获取年份。类似地,user.getMonth() 表示月份,userDate.getDate() 表示日期……我已将 +1 添加到月份,因为月份返回从 0 开始,即第 6 个月返回 5,因此添加了 1。
(3) in return statement year+month+date is done where there is tenary condition to check if month or date is single digit like 1 or 3 then 0 is added before it to make it 01 or 03.
(3) 在 return 语句中年 + 月 + 日完成,其中有十进制条件来检查月或日是否是个位数,如 1 或 3,然后在它之前添加 0 使其成为 01 或 03。
回答by fahreyad
function formatDate(userDate) {
var first = userDate.indexOf("/");
var last = userDate.lastIndexOf("/");
var months = userDate.substring(0, first);
var years = userDate.substring(last + 1);
var days = userDate.substring(last, 3);
return (years + months + days);
}
console.log(formatDate("12/31/2014"));
回答by Ramona Liliana
function formatDate(userDate) {
let userdate = userDate.split('/');
let [month, day, year] = userdate;
if (day.length === 1) {
day = `0${day}`;
}
if (month.length === 1) {
month = `0${month}`;
}
return `${year}${month}${day}`;
}
console.log(formatDate("12/1/2014"));