I am trying to convert a date string into a date object within javascript. My date has the following format:
"13.02.2015 12:55"
My current approach was:
var d = new Date("13.02.2015 12:55");
But this didnt work and always returns invalid date. If I enter a date as "12.02.2015 12:55" it works in chrome but not in firefox.
I guess this is because he thinks the first part is the month, but in germany this is not the case.
How can I get this to work?
use moment.js:
var date = moment("13.02.2015 12:55", "DD.MM.YYYY HH.mm").toDate();
Update 2022-05-28:
Meanwhile the project status of moment.js has changed. Therefore I strongly suggest to read https://momentjs.com/docs/#/-project-status/ and observe the recommendations.
try the ISO 8601 format,
or better yet, read this http://www.ecma-international.org/ecma-262/5.1/#sec-15.9
Edit: if you have no other choice than to get it in that format though, i guess you'll need something like this:
function DDMMYYYY_HHMMtoYYYYMMDD_HHMM($DDMMYYYY_HHMM) {
var $ret = '';
var $foo = $DDMMYYYY_HHMM.split('.');
var $DD = $foo[0];
var $MM = $foo[1];
var $YYYY = $foo[2].split(' ') [0].trim();
var $HH = $foo[2].split(' ') [1].split(':') [0].trim();
var $MMM = $foo[2].split(' ') [1].split(':') [1].trim();
return $YYYY + '-' + $MM + '-' + $DD + ' ' + $HH + ':' + $MMM;
}
var d=new Date(DDMMYYYY_HHMMtoYYYYMMDD_HHMM('13.02.2015 12:55'));
Related
Why is the first date invalid? I don't understand.
https://jsfiddle.net/r4dgjdn6/1/
$(document).ready(function() {
alert(new Date('19.12.2016 14:00'));
alert(new Date('12.12.2016 14:00'));
});
I want to calculate date difference but i keep getting the Invalid Date error.
You can use the library http://momentjs.com/ and use it like this:
var a = moment('19.12.2016 14:00', 'DD.MM.YYYY mm:ss');
var b = moment('12.12.2016 14:00', 'DD.MM.YYYY mm:ss');
//to calculate the diff
a.diff(b);
because the 'date' constructor can get specific "date format" as parameters
for example :
alert(new Date('Mon Dec 19 2016 14:00:00'));
take a look at this :
http://www.w3schools.com/js/js_dates.asp
EDIT:
if it is always in this format you can use this "quick" code to parse your string into the right format:
var inputString = '19.12.2016 14:00';
var tmpArray = inputString.split('.');
var result = tmpArray[1] + "-" + tmpArray[0] + "-" + tmpArray[2].split(' ')[0] + " " + tmpArray[2].split(' ')[1];
alert(new Date(result));
I have a common date field having a displayDD-MM-YYYY but the real value stored in database is YYYY-MM-DD. The problem is this value is also transmitted to a remote server inside a simple text field (having readonly properties) and I would like interact on this field for change his display in DD-MM-YYYY.
I don't want touch something in database structure for change the way on how the date is stored. I precise I don't have access to html of this remote server but I'm allowed to modify some field by putting code in JS file.
I looked here and in some forum but I don't find a solution and due to my poor javascript knowledge I'm stuck. Thank.
Use inbuilt javascript functions to build the format you want. PArse the string in to a date object and use the following functions to create your desired format
getDate() -> to get date
getMonth() -> to get month
getFullYear() -> to get year
Example
//var birth_date = document.getElementById('birth_date');
//use birth_date instead of hard coded date
//var day = new Date(Date.parse(birth_date));
var day = new Date(Date.parse("2013-09-02"));
alert(day.getDate() + "-" + day.getMonth() + "-" + day.getFullYear());
//set value
document.getElementById('birth_date').value = day.getDate() + "-" + day.getMonth() + "-" + day.getFullYear();
JSFIDDLE
Say you have a string var s = '1989-05-06';. You can get the year, month and day separately like so:
var my_date = s.split('-');
var year = my_date[0];
var month = my_date[1];
var day = my_date[2];
Then, you can display the string below (or organize the day, month and year in any format you would like):
var display_str = '' + day + '-' + month + '-' + year;
You can catch the form submit event and change the value before it is sent:
Let's say you have a form #myForm:
var form = document.getElementById('myForm');
To catch submission:
try {
form.addEventListener("submit", changeValue, false);
} catch(e) {
form.attachEvent("onsubmit", changeValue); //Internet Explorer 8-
}
Now you can change the desired value inplace.
function changeValue(){
var field = document.getElementById('idOfField');
field.value = field.value.split('-').reverse().join('-');
}
well, we can do that using simple javascript function.
we just need to pass server date(YYYY-MM-DD) and it wll return expected date (DD-MM-YYYY) format.
function convertDate(serverDate) {
var dateCollection = serverDate.match(/\d+/g),
year = dateCollection[0],
month = dateCollection[1],
day = dateCollection[2];
return day + '-' + month + '-' + year;
}
Example:-
convertDate('2013-09-02'); // (YYYY-MM-DD) format
output:-
'02-09-2013' //(DD-MM-YYYY) format
Hope this will help you...
I've got a problem with date object in IE8, and some older browsers. On website I have input hidden, where I keep date, and after change new date should be in that field.
On my machine everything is fine, but on some others I get NaN-NaN-NaN, that's my code:
var date = new Date($('#curDate').val());
//date.setDate(date.getDate() - 7);
var dateMsg = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
alert(dateMsg);
When I run this file (php), in hidden input I've got Monday's date from the current week 2013-03-25.
This alert return me NaN-N.. on Win XP IE8, and on very old mac, I recon it's problem with object. How to take date value and convert it to object in javascript?
Never use new Date(some_string) - it's unreliable because it depends on the user's locale.
Break the string into its yy/mm/dd components yourself and then call new Date(y, m - 1, d)
Problem with your hyphens..
Convert your hyphens('-') with slashes('/')
var dateStr=$('#curDate').val();
var a=dateStr.split(" ");
var d=a[0].split("-");
var t=a[1].split(":");
var date = new Date(d[0],(d[1]-1),d[2],t[0],t[1],t[2]);
or
var date=new Date(convertToSlash($('#curDate').val()));
function convertToSlash(string){
var response = string.replace(/-/g,"/");
return response;
}
You can also use new Date(some_string) format. It's reliable. However, the datestring must be in ISO format that is yyyy/mm/dd.
I am able to get the output format that I need, but not the correct time. I need it in GMT (which is +4 hours)
var dt = new Date();
var dt2 = dt.toString('yyyyMMddhhmmss');
Any ideas? The output looks like:
20120403031408
I am able to get the GMT in standard string format by doing:
dt.toUTCString();
but im unable to convert it back to the yyyyMMddhhmmss string
EDIT: I am using the date.js library
date.js's toString(format) doesn't have an option to specify "UTC" when formatting dates. The method itself (at the bottom of the file) never references any of Date's getUTC... methods, which would be necessary to support such an option.
You may consider using a different library, such as Steven Levithan's dateFormat. With it, you can either prefix the format with UTC:, or pass true after the format:
var utcFormatted = dateFormat(new Date(), 'UTC:yyyyMMddhhmmss');
var utcFormatted = dateFormat(new Date(), 'yyyyMMddhhmmss', true);
// also
var utcFormatted = new Date().format('yyyyMMddhhmmss', true);
You can also write your own function, as Dominic demonstrated.
The key is to use the getUTC functions :
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
/* use a function for the exact format desired... */
function ISODateString(d){
function pad(n) { return n < 10 ? '0'+n : n }
return d.getUTCFullYear() + '-'
+ pad(d.getUTCMonth() +1) + '-'
+ pad(d.getUTCDate()) + 'T'
+ pad(d.getUTCHours()) + ':'
+ pad(d.getUTCMinutes()) + ':'
+ pad(d.getUTCSeconds()) + 'Z'
}
var d = new Date();
console.log(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z
I use Google Analytics, and the first thing I want to check every day is the current day's statistics. But there's no way to bookmark the current day.
The URL for any given day is: https://www.google.com/analytics/reporting/dashboard?id=XXXXXXX&pdr=20110921-20110921
You can see a date range at the end of the URL. 20110921 meaning 9-21, 2011.
How can I write a little javascript bookmarklet for Firefox to change the URL to the current date depending on what day I click on it?
Try this - it uses a Date object to get the date:
var date = new Date();
var str = "";
str += date.getFullYear();
str += pad2(date.getMonth() + 1);
str += pad2(date.getDate());
function pad2(n) {
var str = String(n);
if(str.length < 2)
str = "0" + str;
return str;
}
location.href = "https://www.google.com/analytics/reporting/dashboard?id=XXXXXXX&pdr="+str+"-"+str;
Bookmarklet:
javascript:(function(){function d(a){a=String(a);a.length<2&&(a="0"+a);return a}var c=new Date,b="";b+=c.getFullYear();b+=d(c.getMonth()+1);b+=d(c.getDate());location.href="https://www.google.com/analytics/reporting/dashboard?id=XXXXXXX&pdr="+b+"-"+b})();
JavaScript has date methods that can individually give the parts of a date, but .toISOString() might perhaps work for your application most concisely. Very little string manipulation would have to be performed on the result to get the UTC date in the correct format. For example:
javascript:
d = new Date().toISOString().slice(0, 10).replace(/-/g, '');
location = "https://www.google.com/analytics/reporting/dashboard?id=XXXXXXX&pdr="
+ d + "-" + d;
To build on the answer by #PleaseStand - Firefox even has a non-standard Date.toDateLocale() function. So the whole thing can be simplified even further:
javascript:void(location.href = "https://www.google.com/analytics/reporting/dashboard?id=XXXXXXX&pdr=" +
new Date().toLocaleFormat("%Y%m%d-%Y%m%d"))
Customize this code below with your Google Analytics ID, timezone offset, and other desired parameters.
Use a site like this to convert JavaScript to a bookmarklet.
Rejoice.
var gaID = YOUR_ID;
var hourOffset = 8;
var rowCount = 50;
var utcDate = new Date(new Date().toUTCString());
utcDate.setHours(utcDate.getHours() - hourOffset);
var localDate = new Date(utcDate);
var todayDate = localDate.toISOString().split("T")[0].replace(/-/g, "");
location.href = "https://analytics.google.com/analytics/web/#/report/advertising-adwords-keywords/" + gaID +"/_u.date00=" + todayDate + "&_u.date01=" + todayDate + "&explorer-table.plotKeys=%5B%5D&explorer-table.rowCount=" + rowCount;
I know this is a really old thread, but it is still relevant.
I found that if you set up your report using todays date, then edit the URL and use a future date, it will default to the current date's statistics.
For example, I use this:
https://analytics.google.com/analytics/web/#/dashboard/xxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxx/_u.date00=20221130&_u.date01=20221130/
The date codes are both the same date 2 years in the future. This causes analytics to use show the current dates stats.