简体   繁体   中英

convert string into datetime object in javascript

I have to send Date object for current date to my back end from javascript

What I am doing is

var currentDate = new Date();
var dateString = currentDate.getMonth() + "-"
  + currentDate.getDate() + "-" + currentDate.getFullYear() + " "
  + currentDate.getHours() + ":" + currentDate.getMinutes() + ":"
  + currentDate.getSeconds();
var newDate = new Date(Date.parse(dateString));

But it is saying Invalid Date to newDate .

I have to send 3-10-2013 6:10:25 PM as datetime object to backend.

var currentDate = new Date(),
    utcYear = currentDate.getUTCFullYear(),
    utcMonth = ('0' + currenctDate.getUTCMonth()).slice(-2),
    utcDay = ('0' + currentDate.getUTCDate()).slice(-2),
    fullDateString = utcMonth.toString() + '/' + utcDay.toString() + '/' + utcYear.toString();

Same principle if you want to get the time part as well.

Instead of putting - in between the month/date and date/year, just put spaces.

var currentDate = new Date(),
    dateString = currentDate.getMonth() + " " + 
                  currentDate.getDate() + " " + 
              currentDate.getFullYear() + " " + 
                 currentDate.getHours() + ":" + 
               currentDate.getMinutes() + ":" + 
               currentDate.getSeconds(),
    newDate = new Date(dateString);

console.log(newDate)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM