convert string to Date Javascript - javascript

Trying to convert a string to Javascript Date.
My string:
var fullDate = this.date + " " + this.time + ":00";
gives an output: 24/12/2016 02:00:00
but trying to convert it in js Date object like:
var k = new Date(fullDate);
gives the output: Invalid Date
or even: var k = Date.parse(fullDate);
gives the output: NaN
Any help is welcome.
I was following instructions from http://www.datejs.com/ so far

Your format is invalid. Valid format is month/day/year, so try:
var fullDate = "12/24/2016 02:00:00";
var k = new Date(fullDate);
Hope I could help!

I've just posted an answer/question for this.
Here's my answer
In summary you need to format the string to a standardized format first and then you can use that string with the new Date(string) method. This work for many browsers (IE9+, Chrome and Firefox).
stringFormat = moment(dateObject).format("YYYY-MM-DDTHH:mm:ss");
date = new Date(stringFormat);

That's happening because you don't provide a valid date format for the new Date. So the date format is incorrect. The default date format in JavaScript is dd/mm/yyyy.
The date should be like(mm/dd/yyyy):
12/24/2015
And then you can use var k = new Date(fullDate);
A pure javascript solution to format the date(without moment.js):
var fullDate = "24/12/2016 02:00:00";
fullDate = fullDate.split(' ');
var date = fullDate[0].split(/\//);
var time = fullDate[1];
var newDate = date[1] + '/' + date[0] + '/' + date[2] + ' ' + time;
var k = new Date(newDate);

Related

How can I convert timestamp to date format yyyy-MM-dd'T'HH:mm:ssXXX?

I would like to know if there's a way to convert a timestamp to yyyy-MM-dd'T'HH:mm:ssXXX date format?
I can convert it to ISO using toISOString but it add Z at the end of the string.
Thank you.
var d = new Date();
var datestring = d.getDate() + "-" +
(d.getMonth() + 1) + "-" +
d.getFullYear() + "-T " +
d.getHours() + ":" +
d.getMinutes();
If you really do not want to use an external library like moment.js (which i would strongly recommend), as you stated in your comment, you will have to implement a function for that yourself, as regular javascript does not provide a function for this (as far as i know).
You can create an object of javascripts built-in Date class from a unix timestamp by using
var unixTimestamp = 1566394163;
//multiply with 1000 as Date expects milliseconds
var date = new Date(unixTimestamp * 1000);
Then you could build the output string yourself, by using something along this
var dateString = "";
dateString += date.getUTCFullYear()+"-";
dateString += date.getUTCMonth()+"-";
dateString += ...
On the other hand, if the Z at the end of the string is the only thing that bothers you about the format provided by toISOString() as a workaround you could use its output and remove the last character of it
var dateString = date.toISOString();
var newDateString = dateString.substr(0, dateString.length -1);
Please try using below code to convert timestamp to date format.
var date = new Date(timestamp*1000);
var year = date.getFullYear();
var month = months_arr[date.getMonth()];
var day = date.getDate();
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
Display date time in any format you want.

How to apply moment.js to existing variables in html

Is there a way to form the current date and time into a moment.js using these variables?
var x = new Date(document.lastModified);
var y = new Date();
document.writeln('The last modified date is: ' + x + ' and Date is: ' + y);
const last = moment(document.lastModified, "MM/DD/YYYY");
const now = moment();
document.write('The last modified date is: ' + last.format("YYYY-MM-DD") + ' and Date is: ' + now.format("YYYY-MM-DD"));
<script src="https://momentjs.com/downloads/moment.js"></script>
You can use n.toISOString(); to convert your date to ISO format and then parse it in momentjs.
var date = moment(n.toISOString()).format('DD-MM-YYYY');
Example:
var n = new Date();
n.toISOString();
var date = moment(n.toISOString()).format('DD-MM-YYYY');
console.log(date);

JavaScript New Date from a 12 hour format date and time string

Example string: 2014-12-31 11:59 pm
As it stands, JavaScript isn't even parsing the time as the resulting time code returns 12:00 am regardless of what time I provide.
Output after new Date("2014-12-31 11:59 pm") results in: 2014-12-31 12:00 am
EDIT:
Even after expecting a format and manually parsing the string, the new Date() constructor isn't behaving...
var sourceTime = "2014-12-31 11:59 pm";
var dateRaw = sourceTime.split(' ');
var dateYMD = dateRaw[0].split('-');
var dateTime = dateRaw[1].split(':');
var dateAmPm = dateRaw[2].toLowerCase();
// Adjust human month to system month...
dateYMD[1] = (parseInt(dateYMD[1]) - 1).toString();
// Convert 12h to 24h...
if(dateAmPm == 'pm') {
if(parseInt(dateTime[0]) < 12) dateTime[0] = (parseInt(dateTime[0])+12).toString();
} else {
if(parseInt(dateTime[0]) == 12) dateTime[0] = 0;
}
console.log(dateYMD);
console.log(dateTime);
var dateParsed = new Date(dateYMD[0], dateYMD[1], dateYMD[2], dateTime[0], dateTime[1]);
The console log shows the correct values being passed into new Date() but I'm still getting an incorrect output :(
Instead of using the standard Date from JavaScript I always use Moment.js when working with dates. It makes is very easy to work with different formats of dates and customizing everything.
In your case you could do something like:
var datestr = "2014-12-31 11:59 pm";
var date = moment(datestr,"YYYY-MM-DD HH:mm a")
$("#log").text(date.format("HH:mm:SS MMM DD YYYY"));
Here's a jsfiddle to try it.
As far as I know, there is no possibility to change the format of the Date String parsed by the Date constructor or Date.parse() in JavaScript. Format specifications can be found at RFC822 or ECMAScript Standards, and neither does support am/pm.
(links taken from MDN)
I'm fixed my problem.. Solution..
let ThisDate = this.startDate0;
let FinalYear = ThisDate.substring(6,10);
let FinalMonth = ThisDate.substring(3,5);
let FinalDay = ThisDate.substring(0,2);
let FinalHour = ThisDate.substring(11, 13);
let FinalMinutes = ThisDate.substring(14,16);
let FinalDate = FinalYear + "-" + FinalMonth + "-" + FinalDay + " " + FinalHour + ":" + FinalMinutes;

Can I create a date object out of this type of string? in javascript?

Hello I have a XML file and a "created at" tag that stores the date and time like this
2012-09-15 02:08:46
I am trying to create a new Date object so I can easily print out the day month and year. But it doesn't like this format.
something like this
var theDate = new Date(Date.parse(storyDate));
console.log(theDate.getMonth());
theDate = theDate.getDate() + ", " + theDate.getMonth();
thanks
UPDATE: I can get it to work in Chrome but not Firefox.
UPDATE: Found the answer, thanks everybody. why the downvote? It turned out to be a reasonable question. I was missing a T.
var theDate = new Date(Date.parse(storyDate.replace(' ', 'T')));
The 'T' is required between the date and time.(at least in FireFox)
Valid DateTime formats
I would parse the date manually using regular expressions.
var dateStr = "2012-09-15 02:08:46"
var dateRegex = /^(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):(\d{2})$/
var dateParts = dateRegex.exec(dateStr)
var year = dateParts[1],
month = parseInt(dateParts[2], 10) - 1,
day = dateParts[3],
hour = dateParts[4],
minutes = dateParts[5],
seconds = dateParts[6];
var date = new Date(year, month, day, hour, minutes, seconds);
//
console.log(date.getMonth())
console.log(date.getDate() + ", " + date.getMonth());

Convert datetime to valid JavaScript date [duplicate]

This question already has answers here:
Convert date from string in javascript
(4 answers)
Closed 3 years ago.
I have a datetime string being provided to me in the following format:
yyyy-MM-dd HH:mm:ss
2011-07-14 11:23:00
When attempting to parse it into a JavaScript date() object it fails. What is the best way to convert this into a format that JavaScript can understand?
The answers below suggest something like
var myDate = new Date('2011-07-14 11:23:00');
Which is what I was using. It appears this may be a browser issue. I've made a http://jsfiddle.net/czeBu/ for this. It works OK for me in Chrome. In Firefox 5.0.1 on OS X it returns Invalid Date.
This works everywhere including Safari 5 and Firefox 5 on OS X.
UPDATE: Fx Quantum (54) has no need for the replace, but Safari 11 is still not happy unless you convert as below
var date_test = new Date("2011-07-14 11:23:00".replace(/-/g,"/"));
console.log(date_test);
FIDDLE
One can use the getmonth and getday methods to get only the date.
Here I attach my solution:
var fullDate = new Date(); console.log(fullDate);
var twoDigitMonth = fullDate.getMonth() + "";
if (twoDigitMonth.length == 1)
twoDigitMonth = "0" + twoDigitMonth;
var twoDigitDate = fullDate.getDate() + "";
if (twoDigitDate.length == 1)
twoDigitDate = "0" + twoDigitDate;
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear(); console.log(currentDate);
Just use Date.parse() which returns a Number, then use new Date() to parse it:
var thedate = new Date(Date.parse("2011-07-14 11:23:00"));
Use:
enter code var moment = require('moment')
var startDate = moment('2013-5-11 8:73:18', 'YYYY-M-DD HH:mm:ss')
Moment.js works very well. You can read more about it here.
function ConvertDateFromDiv(divTimeStr) {
//eg:-divTimeStr=18/03/2013 12:53:00
var tmstr = divTimeStr.toString().split(' '); //'21-01-2013 PM 3:20:24'
var dt = tmstr[0].split('/');
var str = dt[2] + "/" + dt[1] + "/" + dt[0] + " " + tmstr[1]; //+ " " + tmstr[1]//'2013/01/20 3:20:24 pm'
var time = new Date(str);
if (time == "Invalid Date") {
time = new Date(divTimeStr);
}
return time;
}
You can use moment.js for that, it will convert DateTime object into valid Javascript formated date:
moment(DateOfBirth).format('DD-MMM-YYYY'); // put format as you want
Output: 28-Apr-1993
Hope it will help you :)
new Date("2011-07-14 11:23:00"); works fine for me.
You can use get methods:
var fullDate = new Date();
console.log(fullDate);
var twoDigitMonth = fullDate.getMonth() + "";
if (twoDigitMonth.length == 1)
twoDigitMonth = "0" + twoDigitMonth;
var twoDigitDate = fullDate.getDate() + "";
if (twoDigitDate.length == 1)
twoDigitDate = "0" + twoDigitDate;
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear(); console.log(currentDate);

Categories

Resources