function formatDate (input) {
var datePart = input.match(/\d+/g),
year = datePart[0].substring(2), // get only two digits
month = datePart[1], day = datePart[2];
document.write(new Date(day+'/'+month+'/'+year));
}
formatDate ('2010/01/18');
When i print this i get Thu Jun 01 1911 00:00:00 GMT+0530 (India Standard Time) but the system is actually 3:42 P.M
Use the current date to retrieve the time and include that in the new date. For example:
var now = new Date,
timenow = [now.getHours(),now.getMinutes(),now.getSeconds()].join(':'),
dat = new Date('2011/11/30 '+timenow);
you must give the time:
//Fri Nov 11 2011 00:00:00 GMT+0800 (中国标准时间)
alert(new Date("11/11/11"));
//Fri Nov 11 2011 23:23:00 GMT+0800 (中国标准时间)
alert(new Date("11/11/11 23:23"));
What do you want? Just the time? Or do you want to define a format? Cu's the code expects this format for date: dd/mm/yyyy, changed this to yyyy/mm/dd
Try this:
function formatDate (input) {
var datePart = input.match(/\d+/g),
year = datePart[0],
month = datePart[1], day = datePart[2],
now = new Date;
document.write(new Date(year+'/'+month+'/'+day+" " + now.getHours() +':'+now.getMinutes() +':'+now.getSeconds()));
}
formatDate ('2010/01/18')
Output:
Mon Jan 18 2010 11:26:21 GMT+0100
Passing a string to the Date constructor is unnecessarily complicated. Just pass the values in as follows:
new Date(parseInt(year, 10), parseInt(month, 10), parseInt(day, 10))
You're creating a Date() object with no time specified, so it's coming out as midnight. if you want to add the current date and time, create a new Date with no arguments and borrow the time from it:
var now = new Date();
var myDate = new Date(parseInt(year, 10), parseInt(month, 10), parseInt(day, 10),
now.getHours(), now.getMinutes(), now.getSeconds())
No need to strip the last two characters off the year. "2010" is a perfectly good year.
Related
Updated My Question
How to get total minutes of difference between two dates using pure JavaScript when
Condition (1):: Same month, same year but date changes
newDate: 18/10/2016 0:50
oldDate: 17/10/2016 23:05
Condition (2):: Last date of current month and 1st date of next month
newDate: 1/11/2016 0:50
oldDate: 31/10/2016 23:05
Condition (3):: Last date of year and 1st date of new year
newDate: 1/1/2017 0:50
oldDate: 31/12/2016 23:05
Note: Please have a look newDate and oldDate to understand the conditions.
Thanks
Since you don't want to use a library for parsing date strings, you can write a simple function such as:
// Parse date string in "Sat Dec 31 2016 15:35:57 GMT+0530 (India Standard Time)" format
function parseDate(s) {
// Split into tokens
var b = s.match(/\w+/g) || [];
var months = 'jan feb mar apr may jun jul aug sep oct nov dec'.split(' ');
// Determine offset in minutes
var offSign = /GMT+/.test(s)? -1 : 1;
var offset = b[8].substr(0,2)*60 + +b[8].substr(2,2);
// Create date, applying offset to minutes
var date = new Date(Date.UTC(b[3],
months.indexOf(b[1].toLowerCase()),
b[2],
b[4],
+b[5] + (offSign*offset),
b[6]));
return date;
}
var d = parseDate("Sat Dec 31 2016 15:35:57 GMT+0530 (India Standard Time)")
console.log('UTC: ' + d.toISOString() + '\n' +
'Local: ' + d.toLocaleString());
Completed My Requirements with the below pure JavaScript code
In my code starttime and endtime are
//var startTime = localStorage.getItem("starttime");
//var endTime = new Date();
Example Here.
var startTime = new Date("Sat Dec 31 2016 15:35:57 GMT+0530 (India Standard Time)");
var endTime = new Date("Sun Jan 1 2017 15:35:57 GMT+0530 (India Standard Time)");
var totalMiliseconds = endTime - startTime;
alert(totalMiliseconds);
//output:: 86400000
var totalSeconds = totalMiliseconds/1000;
alert(totalSeconds);
//output:: 86400
var totalMinuts = totalSeconds/60;
alert(totalMinuts);
//output:: 1440
var totalHours = totalMinuts/60;
alert(totalHours);
//output:: 24
And this fulfill my all 3 conditions.
Thank You For Your Support !!!
javascript getTime() returns the number of milliseconds form midnight Jan 1, 1970 and the time value in the Date Object. but,
new Date('Wed Sep 16 2105 05:30:00 GMT+0530').getTime()
// returns 4282502400000
new Date('Tue Oct 26 2015 05:30:00 GMT+0530').getTime()
// returns 1445817600000
Shouldn't the value retuned by the later (Tue Oct 26 2015 05:30:00 GMT+0530) be greater.
I want to find the list dates between a given date (inform of timestamp) and today. I wrote the code below with the assumption that the value returned by getTime() for older dates will always be lesser than newer dates.
var timestamp = new Date('9/15/2105, 12:00:00 AM').getTime();
var startDate = new Date(timestamp);
// Date.UTC() to avoid timezone and daylight saving
var date = new Date(Date.UTC(startDate.getFullYear(),
startDate.getMonth(),
startDate.getDate()
));
var currentDay = new Date();
var currentDayTimestamp = new Date(Date.UTC(currentDay.getFullYear(),
currentDay.getMonth(),
currentDay.getDate()
)).getTime();
// day in millisec, 24*60*60*1000 = 86400000
date = new Date(date.getTime() + 86400000);
var dates = [];
console.info(date + ' : ' + date.getTime());
console.info(new Date(currentDayTimestamp) + ' : ' + currentDayTimestamp);
while(date.getTime() <= currentDayTimestamp) {
var dateObj = {
date: date.getUTCDate(),
month: date.getUTCMonth() + 1,
year: date.getUTCFullYear()
}
dates.push(dateObj);
date = new Date(date.getTime() + 86400000);
}
console.info(JSON.stringify(dates));
OUTPUT:
Wed Sep 16 2105 05:30:00 GMT+0530 (IST) : 4282502400000
Tue Oct 27 2015 05:30:00 GMT+0530 (IST) : 1445904000000
[]
The problem is a typo in your dates. One has the year 2105 which is much larger than 2015.
I need some help with converting unixtime to a specific format. Here is what I am currently working with:
var date = "2014-05-01";
var indexPie = Date.parse(date);
I need indexPie in yyyy-mm-dd format. What I do not understand is that when log
var newDate = new Date(indexPie);
The results is:
Wed Apr 30 2014 18:00:00 GMT-0600 (Mountain Daylight Time)
when it should be:
Thur May 01 2014 18:00:00 GMT-0600 (Mountain Daylight Time)
Why is new Date(indexPie) resulting in Apr 30 and how do I get my correct format of yyyy-mm-dd?
Any suggestions would be great. Thanks.
I resolved the issue with the following:
var date = new Date(indexPie);
var year = date.getUTCFullYear();
var month = date.getUTCMonth() + 1;
var day = date.getUTCDate();
var dateString = year + "-" + month + "-" + day;
You are expecting that the value in date variable: "2014-05-01" will be parsed as in local timezone, but actually it is parsed as in UTC.
You can convert the date from UTC to local timezone like this:
var newDate = new Date(indexPie + new Date().getTimezoneOffset() * 60000);
var date = new Date();
var date2 = new Date();
daysinadvance = document.getElementById('AdvanceDays').value;
date2.setDate(date.getDate()+daysinadvance);
console.log(date2 + date + daysinadvance);
Fri Jan 28 2022 18:13:43 GMT+0000 (GMT Daylight Time)
Mon Apr 28 2014 18:13:43 GMT+0100 (GMT Standard Time)
60
If I pass in a directly typed number so + 60, it works fine but using the variable, I get a date in 2022. All I would like is the date2 to be current date + 60 days so I can update my validation.
Any help please?
Convert the value to a number first, e.g. with the unary plus operator:
var daysinadvance = +document.getElementById('AdvanceDays').value;
// ^ unary plus
Otherwise daysinadvance will be a string and you are doing string concatenation.
I format a date object from a string in javascript but but when i print the formatted date i found it increased two years !!
alert("Date1-Without-conversion:" + document.getElementById(arr[0]).value);
alert("Date2-Without-conversion:" + document.getElementById(arr[1]).value);
it prints:
30/9/2018
04/10/2018
date1Str=document.getElementById(arr[0]).value;
date2Str=document.getElementById(arr[1]).value;
date1 = new Date(date1Str);
date2 = new Date(date2Str);
alert("Date1-After-conversion:" + date1);
alert("Dat2-After-conversion:" + date2);
prints:
Tue Jun 09 2020 00:00:00 GMT+0200(Egypt Standard Time)
Tue Apr 10 2018 00:00:00 GMT+0200(Egypt Standard Time)
the problem is that when i used:
date1.getFullYear() OR `date2.getFullYear()` it prints 2020 !!!
How come ??
Date's parsing leaves something to be desired, as the comments note. You can use this constructor to be succinct
new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]
You need to parse the date by parts.
var date1 = new Date(day, month, year);
For 30/9/2018:
var date1 = new Date(30, 9, 2018);