最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Converting string to date object, adding two hours and converting back to string (JavaScript) - Stack Overflow

programmeradmin1浏览0评论

I have a date string, want to convert it into a date object, add 2 hours and print out the converted date object back to a variable. But I get the error listed bellow:

// dateTime: 2013-09-27 09:50:05 
var dateTime = $("#inputDatetime").val();
var startDate = dateTime;
var date = new Date(startDate);
var duration = 2;
var endDate = date;
endDate.setHours(date.getHours()+duration)
var dateString = endDate.format("dd-m-yy hh:mm:ss");

Error:

Uncaught TypeError: Object [object Date] has no method 'format'

Why do I get this TypeError?

I have a date string, want to convert it into a date object, add 2 hours and print out the converted date object back to a variable. But I get the error listed bellow:

// dateTime: 2013-09-27 09:50:05 
var dateTime = $("#inputDatetime").val();
var startDate = dateTime;
var date = new Date(startDate);
var duration = 2;
var endDate = date;
endDate.setHours(date.getHours()+duration)
var dateString = endDate.format("dd-m-yy hh:mm:ss");

Error:

Uncaught TypeError: Object [object Date] has no method 'format'

Why do I get this TypeError?

Share Improve this question asked Sep 6, 2013 at 17:53 nimrodnimrod 5,74230 gold badges88 silver badges152 bronze badges 1
  • Are you getting the value from datepicker as string? – Vaibs_Cool Commented Sep 6, 2013 at 18:10
Add a ment  | 

4 Answers 4

Reset to default 3

Vaibs, there is no method "format", you can do formating using available methods from Date Object. please don't use plugin

example :

// dd-mm-yy hh:mm:ss

function formatDate(date) {
    return ((date.getDate()<10?'0':'')+date.getDate()) + "-"+ 
        (((date.getMonth()+1)<10?'0':'') + (date.getMonth()+1)) + "-" + 
        date.getFullYear()  + " " +((date.getHours()<10?'0':'')+date.getHours()) + ":" + 
       (date.getMinutes()<10?'0':'') +  date.getMinutes() + ":" + 
       (date.getSeconds()<10?'0':'')  + date.getSeconds(); 
 }

*thank you @donot

Use jquery ui date parser.

http://docs.jquery./UI/Datepicker/parseDate

This is the best function for parsing dates out of strings that I've had the pleasure to work with in js. And as you added the tag jquery it's probably the best solution for you.

.format() is not a valid Date method. JavaScript does not have an easy way to format dates and times with a user-specified format. The best you can do (without separate plugins) is to create your own string by getting each ponent of the date separately, and formatting/concatenating them.

I've used this before and it seems to work!

var dateString = endDate.toString("dd-m-yy hh:mm:ss");

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论