【问题标题】:Reading the date from textbox as a string and converting it into as Date从文本框中读取日期作为字符串并将其转换为日期
【发布时间】:2014-12-03 17:51:48
【问题描述】:

我正在使用 javascript 从文本框中读取日期并尝试将其转换为 Date 对象。但是 我的问题是日期转换为月份,而月份在将字符串转换为日期时转换为日期。 >

示例: 03/12/2014 文本框中的值

实际输出: 03 作为三月, 12 作为日期(错误)

预期输出: 03 作为日期 12 月 12 日(我期待)

使用以下 sn-p 将此字符串转换为日期时

var startTime = document.getElementById("meeting:startTime");
date.js
var stringToDate_startTime=new Date(Date.parse(startTime.value,"dd/mm/yy"));
moment.js
var date1=moment(startTime.value).format('DD-MM-YYYY');

在上面,即使我也使用了 date.js 和 moment.js 文件。但是这些也没有解决我的问题。请任何人都可以帮助我摆脱这个问题。

【问题讨论】:

    标签: javascript date datepicker momentjs datejs


    【解决方案1】:

    试试...

    var from = startTime.value.split("/");
    var newDate = newDate(from[2], from[1] - 1, from[0]);
    

    ...假设包括时间...

    var date_only = startTime.value.split("");
    var from = date_only[0].split("/");
    var newDate = newDate(from[2], from[1] - 1, from[0]);
    

    【讨论】:

    • 我的文本框也包含时间。这是我的文本框值“03/12/2014 23:05”
    • 已调整以适应输入的时间。时间可以在 date_only[1] ... 中访问
    【解决方案2】:

    我不知道接受两个参数的 Date.parse() 方法的实现。您可以在此处查看 Mozilla Date.parse() 方法说明Date.parse() - JavaScript | MDN

    可能值得查看此问题的问题/答案以获取更多信息:Why does Date.parse give incorrect results?

    下一个最佳选择是使用 String.split() 拆分日期并重新排列日期部分

    var dateStr = '03/12/2014 23:05';
    var newDateStr = null;
    var dateParts = dateStr.split('/');
    if (dateParts.length == 3) {
       var day = dateParts[0];
       var month = dateParts[1];
       var yearAndTime = dateParts[2];
    
       // Rearrange the month and day and rejoin the date "12/03/2014 23:05"
       newDateStr = [ month, day, yearAndTime].join('/');
    } else {
       throw new Error('Date not in the expected format.');
    }
    
    var date = new Date(newDateStr);   // JS Engine will parse the string automagically
    
    alert(date);
    

    这不是最优雅的解决方案,但希望能有所帮助。

    【讨论】:

    • 这假设您创建了一个名为“dateStr”的变量。
    • 如果我使用第二种方法,我将无法获得时间。我的文本框也包含时间。
    • 这是我的文本框值“03/12/2014 23:05”
    • 您确定日期将始终采用该格式吗?我更新了代码以反映处理时间。
    猜你喜欢
    • 2019-12-19
    • 2018-07-08
    • 2019-02-12
    • 2021-07-14
    • 2011-11-28
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    相关资源
    最近更新 更多