Convert datetime to valid JavaScript date [duplicate] - javascript

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

Related

convert string to Date 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);

Compatible date formats for browser [duplicate]

This question already has an answer here:
.toLocaleDateString() Not Working in Firefox
(1 answer)
Closed 7 years ago.
I am trying to display "dd-mm-yyyy" date format using the following method
document.getElementById('engStartDate').value=endDate.toLocaleDateString('en-IN',options);
But i am not getting the required format in chrome
Chrome : Jun 11, 2016
Firefox : 11-Jun-2016
It might not directly answer your question, but I suggest you give momentjs a try. It's a Javascript library that allows you to manipulate and format dates and has saved my hide more than once. In your case you would do something like
document.getElementById('engStartDate').value = moment(endDate).format('DD-MM-YYYY);
Date.prototype.toLocaleString doesn't take any arguments and the result is entirely implementation dependent.
If you want a particular format, you can use a library but it's not hard to write a simple function to output dd-mm-yyyy format:
function toDMY(d) {
function z(n){return (n<10?'0':'')+n}
return z(d.getDate()) + '-' + z(d.getMonth()+1) + '-' + d.getFullYear();
}
document.write(toDMY(new Date()));
There is also the ECMAScript Internationalization API 1.0 (ECMA-402) (also on MDN), however it's not well supported yet.
I strongly recommend you to do it manually or use a lib.
I write an example of formate data-time.
var datetimeFormat = function ( datetime, formatStr) {
var obj = null;
if (({}).toString.call(datetime) === '[object Date]') {
obj = datetime;
} else {
datetime = +datetime || 0;
datetime = datetime < +new Date() / 100 ? datetime * 1000 : datetime;
obj = new Date(datetime);
}
var str = formatStr;
var Week = ['Sun', 'Mon', 'Tue', 'Wen', 'Tur', 'Fri', 'Sat'];
str = str.replace(/yyyy|YYYY/, obj.getFullYear());
str = str.replace(/yy|YY/,('0' + obj.getYear() % 100).slice(-2));
var month = obj.getMonth() + 1;
str = str.replace(/MM/, ('0' + month).slice(-2));
str = str.replace(/M/g, month);
str = str.replace(/w|W/g, Week[obj.getDay()]);
str = str.replace(/dd|DD/, ('0' + obj.getDate()).slice(-2));
str = str.replace(/d|D/g, obj.getDate());
str = str.replace(/hh|HH/, ('0' + obj.getHours()).slice(-2));
str = str.replace(/h|H/g, obj.getHours());
str = str.replace(/mm/, ('0' + obj.getMinutes()).slice(-2));
str = str.replace(/m/g, obj.getMinutes());
str = str.replace(/ss|SS/, ('0' + obj.getSeconds()).slice(-2));
str = str.replace(/s|S/g, obj.getSeconds());
return str;
}
document.getElementById('engStartDate').value = datetimeFormat(new Date(), 'dd-MM-yyyy')
<input type='text' id='engStartDate'/>

Setting format and value in input type="date"

Is there any way to set the format of <input type="date" /> ? if no then how can i set date in this field using JavaScript in the default format of type="date". how can i get what will be the format of this field?
EDIT :
Actually i want to show native date-picker of mobile device that's why i picked this type of input. if is there any alternate for that field that also will b good to have.
Sorry if i said anything stupid. Please guide me
The format is YYYY-MM-DD. You cannot change it.
$('#myinput').val('2013-12-31'); sets value
new Date().toISOString().split('T')[0];
try this :)
function getDefaultDate(){
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear()+"-"+(month)+"-"+(day) ;
return today;
}
$(document).ready(function(){
$("#dateid").val( getDefaultDate());
});
Canadian locale happens to follow the same format, too:
new Date().toLocaleDateString('en-CA')
Easier than the above is
var today = new Date().toISOString().substring(0,10); # "2013-12-31"
It's ugly, but it works. :/
var today = new Date().toLocaleString('en-GB').split(' ')[0].split('/').reverse().join('-');
Please check this https://stackoverflow.com/a/9519493/1074944 and try this way also $('input[type="date"]').datepicker().prop('type','text'); check the demo
I think this can help
function myFormatDateFunction(date, format) {
...
}
jQuery('input[type="date"]')
.each(function(){
Object.defineProperty(this,'value',{
get: function() {
return myFormatDateFunction(this.valueAsDate, 'dd.mm.yyyy');
},
configurable: true,
enumerable : true
});
});
function getDefaultDate(curDate){
var dt = new Date(curDate);`enter code here`
var date = dt.getDate();
var month = dt.getMonth();
var year = dt.getFullYear();
if (month.toString().length == 1) {
month = "0" + month
}
if (date.toString().length == 1) {
date = "0" + date
}
return year.toString() + "-" + month.toString() + "-" + date.toString();
}
In function pass your date string.
#cOnstructOr provided a great idea, but it left a comma in place
var today = new Date().toLocaleString('en-GB').split(' ')[0].slice(0,-1).split('/').reverse().join('-');
fixes that
What you want to do is fetch the value from the input and assign it to a new Date instance.
let date = document.getElementById('dateInput');
let formattedDate = new Date(date.value);
console.log(formattedDate);
Here is a simple answer,
Since this is a string, we can use Javascript String slice method to rearrange the characters
<input type="date" id="idate" name="tno"><br>
<button onclick="run()">Run</button>
<p id="demo"></p>
<script>
function run() {
var d = document.getElementById("idate").value;
document.getElementById("demo").innerHTML = d.slice(8, 10) + "/" + d.slice(5, 7) + "/" + d.slice(0, 4);
}
</script>
Source
https://www.w3schools.com/jsref/jsref_slice_string.asp

jQuery: Add 4 weeks to date in format dd-mm-yyyy

I have a string which has a date in the format: dd-mm-yyyy
How I can add 4 weeks to the string and then generate a new string using jQuery / Javascript?
I have
var d = new Date(current_date);
d.setMonth(d.getMonth() + 1);
current_date_new = (d.getMonth() + 1 ) + '-' + d.getDate() + '-' + d.getFullYear();
alert(current_date_new);
but it complains that the string provided is in the incorrect format
EDIT: After a bit of fiddling, here's the solution:
First, split the string to individual parts.
var inputString = "12-2-2005";
var dString = inputString.split('-');
Then, parse the string to a datetime object and add 28 days (4 weeks) to it.
var dt = new Date(dString[2],dString[1]-1,dString[0]);
dt.setDate(dt.getDate()+28);
Finally, you can output the date
var finalDate = dt.GetDate() + "-" + (dt.GetMonth()+1) + "-" + dt.GetYear();
This code should return 12-3-2005.
CAVEATS: It seems JavaScript's Date object takes 0-11 as the month field, hence the -1 and +1 to the month in the code.
EDIT2: To do padding, use this function:
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
and change your output to
var finalDate = pad(dt.GetDate(),2) + "-" + pad(dt.GetMonth()+1,2) + "-" + dt.GetYear();
Check the updated fiddle.
There is no need to convert to mm-dd-yyyy, simple split string by the minus sign and create new Date object with the following code:
var string = '12-02-2012';
var split = string.split('-');
var date = Date(split[2],parseInt(split[1])-1,parseInt(split[0])+1)
date.setDate(date.getDate() + 28);
var fourWeeksLater = date.getDay() + "-"+date.getMonth() +"-"+date.getYear();
This should be working:
var formattedDate = '01-01-2012',
dateTokens = formattedDate.split('-'),
dt = new Date(dateTokens[2], parseInt( dateTokens[1], 10 ) - 1, dateTokens[0]), // months are 0 based, so need to add 1
inFourWeeks = new Date( dt.getTime() + 28 * 24 * 60 * 60 * 1000 );
jsfiddle: http://jsfiddle.net/uKDJP/
Edit:
Using Globalize you can format inFourWeeks:
Globalize.format( inFourWeeks, 'dd-MM-yyyy' ) // outputs 29-01-2012
Instead of writing your own parser for dates, I would use moment.js.
To parse your date:
var date = moment('14-06-2012', 'DD-MM-YYYY');
To add 4 weeks to it:
date.add('weeks', 4);
Or in one go:
var date = moment('14-06-2012', 'DD-MM-YYYY').add('weeks', 4);
And convert it to string:
var dateString = date.format('DD-MM-YYYY');

Convert date in javascript

How can I convert this date:
2011-11-02T10:41:43+0000
Into this using JavaScript:
02/11
Thankful for all help!
If that date is a string, a simple RegEx can offer the desired results:
var date = "2011-11-02T10:41:43+0000";
date = date.match(/-(\d{1,2})-(\d{1,2})T/);
date = date[2] + "/" + date[1]; // date = "02/11"
var d = new Date('2011-11-02T10:41:43+0000'),
dateString = d.getDate()+'/'+(d.getMonth()+1);
console.log(dateString); // 2/11
You could do this
var d = new Date('2011-11-02T10:41:43+0000');
var e = d.getUTCDate() + '/' + (d.getUTCMonth() + 1);
alert(e);
Example: http://jsfiddle.net/pRbZ2/
Assuming that the 11 you want is the month and not the year

Categories

Resources