格式输入从M / D / YYYY到YYYYMMDD

时间:2015-02-12 12:18:41

标签: javascript

编写一个功能,将格式为 M / D / YYYY 的用户输入日期转换为API所需的格式( YYYYMMDD )。参数“userDate”和返回值是字符串。

例如,它应将用户输入的日期“12/31/2014”转换为适用于API的“20141231”

function formatDate(userDate) 
{
     userDate = new Date();
     y = userDate.getFullYear();
     m = userDate.getMonth();
     d = userDate.getDate();

     return y + m + d;
}

我的代码有什么问题吗?

无法通过在线测试。

10 个答案:

答案 0 :(得分:8)

代码有五个问题。

  • 它忽略输入参数并改为使用当前时间(Date())。
  • 它假设运行它的计算机使用m / d / y日期格式来解析字符串(如果它实际上已经解析了字符串)。
  • getMonth方法返回月份索引,而不是月份编号,因此您必须为其添加一个。
  • 它使用addition将值放在一起而不是字符串连接。
  • 它不会将月份和日期格式化为两位数。

忽略日期格式问题,可以使用以下方法修复其他格式:

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;
}

您可以重新排列字符串中的字符,而不是将字符串解析为日期,并将其格式化为字符串。这避免了日期格式问题:

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];
}

答案 1 :(得分:2)

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

作为初学者,这是我能够做到这一点的最简单方法。我将它拆分,添加0然后将其分类到正确的位置对我来说更有意义。

答案 2 :(得分:1)

按照代码中的注释进行操作 - 逐步显示解决问题的单向

&#13;
&#13;
// 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");
&#13;
<div id="result">Result: </div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您正在使用带有整数的+,您必须将它们转换为字符串。

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);
}

此外,您还需要在月和日添加前导零。

示例:

console.log(formatDate('2/12/2015'));

将写入日志20150212

console.log(formatDate('1/1/2015'));

将写入日志20150101

答案 4 :(得分:0)

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"));

答案 5 :(得分:0)

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"));

更多细节:

(1)userDate = new Date(userDate)=&gt;创建Date对象的实例。

(2)userDate.getFullYear()从userDate获取年份。类似于月份的user.getMonth()和日期的userDate.getDate()...我已经将月份+1添加到月份,因为月份返回开始为0,即第6个月它返回5,因此添加了1。

(3)在退货声明年份+月份+日期是在有条件的情况下完成,以检查月份或日期是否为1或3之类的单个数字,然后在它之前添加0以使其成为01或03。

答案 6 :(得分:0)

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"));

答案 7 :(得分:0)

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"));

答案 8 :(得分:0)

~\Miniconda3\lib\site-packages\matplotlib\axes\_axes.py in fill_between(self, x, y1, y2, where, interpolate, step, **kwargs)
   5226 
   5227         # Handle united data, such as dates
-> 5228         self._process_unit_info(xdata=x, ydata=y1, kwargs=kwargs)
   5229         self._process_unit_info(ydata=y2)
   5230 

~\Miniconda3\lib\site-packages\matplotlib\axes\_base.py in _process_unit_info(self, xdata, ydata, kwargs)
   2123             return kwargs
   2124 
-> 2125         kwargs = _process_single_axis(xdata, self.xaxis, 'xunits', kwargs)
   2126         kwargs = _process_single_axis(ydata, self.yaxis, 'yunits', kwargs)
   2127         return kwargs

~\Miniconda3\lib\site-packages\matplotlib\axes\_base.py in _process_single_axis(data, axis, unit_name, kwargs)
   2106                 # We only need to update if there is nothing set yet.
   2107                 if not axis.have_units():
-> 2108                     axis.update_units(data)
   2109 
   2110             # Check for units in the kwargs, and if present update axis

~\Miniconda3\lib\site-packages\matplotlib\axis.py in update_units(self, data)
   1496 
   1497         if neednew:
-> 1498             self._update_axisinfo()
   1499         self.stale = True
   1500         return True

~\Miniconda3\lib\site-packages\matplotlib\axis.py in _update_axisinfo(self)
   1532             self.isDefault_label = True
   1533 
-> 1534         self.set_default_intervals()
   1535 
   1536     def have_units(self):

~\Miniconda3\lib\site-packages\matplotlib\axis.py in set_default_intervals(self)
   2170                 if info.default_limits is not None:
   2171                     valmin, valmax = info.default_limits
-> 2172                     xmin = self.converter.convert(valmin, self.units, self)
   2173                     xmax = self.converter.convert(valmax, self.units, self)
   2174             if not dataMutated:

~\Miniconda3\lib\site-packages\pandas\plotting\_matplotlib\converter.py in convert(values, units, axis)
    207             values = [PeriodConverter._convert_1d(v, units, axis) for v in values]
    208         else:
--> 209             values = PeriodConverter._convert_1d(values, units, axis)
    210         return values
    211 

~\Miniconda3\lib\site-packages\pandas\plotting\_matplotlib\converter.py in _convert_1d(values, units, axis)
    213     def _convert_1d(values, units, axis):
    214         if not hasattr(axis, "freq"):
--> 215             raise TypeError("Axis must have `freq` set to convert to Periods")
    216         valid_types = (str, datetime, Period, pydt.date, pydt.time, np.datetime64)
    217         if isinstance(values, valid_types) or is_integer(values) or is_float(values):

TypeError: Axis must have `freq` set to convert to Periods

答案 9 :(得分:0)

function formatDate(userDate) {
  // format from M/D/YYYY to YYYYMMDD
  let [month,date,year] = userDate.split("/");
  month = (month.length === 1) ? "0"+month : month;
  date = (date.length === 1) ? "0"+date : date;
  
  return year+month+date
}

console.log(formatDate("1/31/2014"));