Is there a way I could get the year, month (0 based) and day from '03/05/2013'
If so, how?
Thanks
Is there a safe way to do it that can check if it is in the correct format?
You have the Date.parse method which parses a Date string and returns its timestamp, so you can call new Date().
Something like this:
new Date(Date.parse('03/06/2013'))
Most easy is using the split() function, i think:
var date = "03/05/2013";
var dateParts = date.split("/");
var day = dateParts[0];
var month = dateParts[1];
var year = dateParts[2];
http://jsfiddle.net/s7ma2/1/
Related
I have this date in string format:
"05/2016" or "12/2015"
How can I convert the dates above in string format to Date() javascript object?
Date constructor accepts params in next order: year, month, day, hours, minutes, seconds, milliseconds, so simply parse string and pass it into Date constructor.
var data = "05/2016".split('/');
// Add + before year to convert str into number. Decrease second param because month starts from 0..11.
var date = new Date(+data[1],data[0] - 1);
console.log(date);
Also, you can convert your string to format which would be parsed correctly by new Date ( See more about dateString in MDN Date.parse description.
// convert string "05/2016" -> "2016-05"
var dateString = "05/2016".split('/').reverse().join('-');
var date = new Date(dateString);
console.log(date);
The previous answers are not correct - they get either the month or the year wrong. This is right (see the comment by Frédéric Hamidi)
var str = "12/2015";
var arr = str.split('/');
var date = new Date(parseInt(arr[1], 10), parseInt(arr[0], 10)-1)
console.log(date)
You can split string to get an array then use Date constructor.
new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
var str = "12/2015";
var arr = str.split('/');
var date = new Date(parseInt(arr[1], 10), parseInt(arr[0], 10) - 1)
console.log(date)
You might want to look at Converting string to date in js
I had a similar issue and stumbled upon this existing link.
I have the following code which I get from parameters in the URL.
This is what I have in the URL
&dateStart=15.01.2015&timeStart=08%3A00&
After getting the parameters I have the following: 15.01.2015:08:00
Using Javascript how can I parse this string to get the date in milliseconds?
Date.parse(15.01.2015:08:00)
But obviously this doesn't work.
Date.parse(15-01-2015)
This works and I can change this but then how do I add or get the milliseconds from the time??
This is quite possibly the ugliest JavaScript function I've written in my life but it should work for you.
function millisecondsFromMyDateTime(dateTime) {
var dayMonth = dateTime.split('.');
var yearHourMinute = dayMonth[2].split(':');
var year = yearHourMinute[0];
var month = parseInt(dayMonth[1]) - 1;
var day = dayMonth[0];
var hour = yearHourMinute[1];
var minute = yearHourMinute[2];
var dateTimeObj = new Date(year, month, day, hour, minute, 0, 0);
return dateTimeObj.getTime();
}
It will work with the format that your DateTime is in aka day.month.year:hours:minutes.
You can achieve it using Javascript Date Object and JavaScript getTime() Method:
var dateString="01.15.2015 08:00";
var d = new Date(dateString);
console.log(d);
var ms=d.getTime();
console.log(ms);
ms+=10000;
console.log(new Date(ms));
Here is a DEMO Fiddle.
Note: Change your date string from 15.01.2015:08:00 to "01.15.2015 08:00" because it's not a valid Date format.
Check for format
Date() in javascript :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Format allowed :
https://www.rfc-editor.org/rfc/rfc2822#page-14
You can try to use moment.js library like this:
moment('15.01.2015 08:00', 'DD.MM.YYYY HH:mm').milliseconds()
Just for the sake of completion, you can always extract the information and create a Date object from the extracted data.
var dateStart = '15.01.2015'
var timeStart = '08:00';
var year = dateStart.substring(6,10);
var month = dateStart.substring(3,5);
var day = dateStart.substring(0,2);
var hour = timeStart.substring(0,2);
var mins = timeStart.substring(3,5);
var fulldate = new Date(year, month-1, day, hour, mins);
console.log(fulldate.getTime());
I am reading the date from textbox by using javascript and trying to convert it as Date object.But my problem is date is converting as month and month is converting as date when converting the string to date.
Example:
03/12/2014 the value in the textbox
Actual Output:
03 as March,
12 as date (Its wrong)
Expected Output:
03 as date
12 as December (I am expecting)
While converting this string to date by using following snippet
var startTime = document.getElementById("meeting:startTime");
date.js
var stringToDate_startTime=new Date(Date.parse(startTime.value,"dd/mm/yy"));
moment.js
var date1=moment(startTime.value).format('DD-MM-YYYY');
In the above even i have used date.js and moment.js files also.But those also did not solve my problem.Please can anyone help me out to get rid out of this.
Try ...
var from = startTime.value.split("/");
var newDate = newDate(from[2], from[1] - 1, from[0]);
... assuming time included ...
var date_only = startTime.value.split("");
var from = date_only[0].split("/");
var newDate = newDate(from[2], from[1] - 1, from[0]);
I am not aware of an implementation of the Date.parse() method that accepts two arguments. You can view the Mozilla Date.parse() method description here Date.parse() - JavaScript | MDN.
It might be worth looking at the question/answer of this question for some more information: Why does Date.parse give incorrect results?
The next best option would be to split the date using String.split() and to rearrange the date parts
var dateStr = '03/12/2014 23:05';
var newDateStr = null;
var dateParts = dateStr.split('/');
if (dateParts.length == 3) {
var day = dateParts[0];
var month = dateParts[1];
var yearAndTime = dateParts[2];
// Rearrange the month and day and rejoin the date "12/03/2014 23:05"
newDateStr = [ month, day, yearAndTime].join('/');
} else {
throw new Error('Date not in the expected format.');
}
var date = new Date(newDateStr); // JS Engine will parse the string automagically
alert(date);
This isn't the most elegant solution, but hopefully that helps.
This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 3 years ago.
I want to get today's date in the format of mm-dd-yyyy
I am using var currentDate = new Date();
document.write(currentDate);
I can't figure out how to format it.
I saw the examples var currentTime = new Date(YY, mm, dd); and currentTime.format("mm/dd/YY");
Both of which don't work
I finally got a properly formatted date using
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;//January is 0!`
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm}
var today = mm+'/'+dd+'/'+yyyy;
document.write(today);'`
This seems very complex for such a simple task.
Is there a better way to get today's date in dd/mm/yyyy?
Unfortunately there is no better way, but instead of reinventing the wheel, you could use a library to deal with parsing and formatting dates: Datejs
<plug class="shameless">
Or, if you find format specifiers ugly and hard to decipher, here's a concise formatting implementation that allows you to use human-readable format specifiers (namely, the Date instance getters themselves):
date.format("{Month:2}-{Date:2}-{FullYear}"); // mm-dd-yyyy
</plug>
var today = new Date();
var strDate = 'Y-m-d'
.replace('Y', today.getFullYear())
.replace('m', today.getMonth()+1)
.replace('d', today.getDate());
Simple answer is no. Thats the only way to do it that I know of.
You can probably wrap into a function that you can reuse many times.
date.js is what you need. For example, snippet below is to convert a date to string as Java style
new Date().toString('M/d/yyyy')
function dateNow(splinter){
var set = new Date();
var getDate = set.getDate().toString();
if (getDate.length == 1){ //example if 1 change to 01
getDate = "0"+getDate;
}
var getMonth = (set.getMonth()+1).toString();
if (getMonth.length == 1){
getMonth = "0"+getMonth;
}
var getYear = set.getFullYear().toString();
var dateNow = getMonth +splinter+ getDate +splinter+ getYear; //today
return dateNow;
}
format this function is mm dd yyyy
and the dividing you can choice and replace if you want... for example
dateNow("/") you will get 12/12/2014
There is nothing built in, but consider using this if you are already using jQuery (and if not, then you should consider that as well!)
http://plugins.jquery.com/project/jquery-dateFormat
(new Date()).format("MM-dd-yyyy")
N.B. month is "MM" not "mm"
function appendZeros(value,digits){
var c= 1;
initValue = value;
for(i=0;i<digits-1;i++){
c = c*10;
if( initValue < c ){
value = '0' + value;
}
}
return value;
}
i have a string which, i want to compare with a javascript datetime object.
how to convert string "1/1/1912" into datetime using JavaScript so that i can compare like
if (EDateTime > ('1/1/1912')) {...}
You could do this simply with a split if you can guarantee the date format.
var dateArray = '1/1/1912'.split("/");
new Date(dateArray[2], dateArray[1], dateArray[0]);
var dateArray = '2012-02-17 01:10:59'.split(' ');
var year = dateArray[0].split('-');
var time = dateArray[1].split(':');
var finishDate = new Date(year[0], year[1], year[2], time[0], time[1], time[2])
How about using DateJS library?
It can convert 1/1/1912 to Monday, January 01, 1912 12:00:00 AM easily
Convert your string to timestamp with Date object.
I found something like:
function toTimestamp(year,month,day,hour,minute,second){
var datum = new Date(Date.UTC(year,month-1,day,hour,minute,second));
return datum.getTime()/1000;
}
Year, month and day parts get with regular expressions.
This library may be helpful.