Convert LocaleTimeString Back to Date - javascript

Firstly, I convert a datetime to date and time respectively.
var d = new Date();
var localeDate = d.toLocaleDateString();
var localeTime = d.toLocaleTimeString();
However, when i try to convert it back to date object
var convertLocaleDate = new Date(localeDate); // success
var convertLocaleTime = new Date(localeTime); // not a valid date format
How can i convert localeTime back to valid date?

look carefully. You are not converting localeDate back to the original date. The time portion is set to 00:00:00
You cannot achieve the result you are trying for.
new Date() will work for the arguments mentioned below
new Date();
new Date(value);
new Date(dateString);
new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
more info here :
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date
giving localeTime as an argument doesn't work because the Date constructor will not know what date/month/year that time is for.
On the other hand localeDate worked because the date/month/year were known and time was set as default to 12am as default

Related

Material2 Datepicker - Convert date to timestamp without time [duplicate]

Can I convert iso date to milliseconds?
for example I want to convert this iso
2012-02-10T13:19:11+0000
to milliseconds.
Because I want to compare current date from the created date. And created date is an iso date.
Try this
var date = new Date("11/21/1987 16:00:00"); // some mock date
var milliseconds = date.getTime();
// This will return you the number of milliseconds
// elapsed from January 1, 1970
// if your date is less than that date, the value will be negative
console.log(milliseconds);
EDIT
You've provided an ISO date. It is also accepted by the constructor of the Date object
var myDate = new Date("2012-02-10T13:19:11+0000");
var result = myDate.getTime();
console.log(result);
Edit
The best I've found is to get rid of the offset manually.
var myDate = new Date("2012-02-10T13:19:11+0000");
var offset = myDate.getTimezoneOffset() * 60 * 1000;
var withOffset = myDate.getTime();
var withoutOffset = withOffset - offset;
console.log(withOffset);
console.log(withoutOffset);
Seems working. As far as problems with converting ISO string into the Date object you may refer to the links provided.
EDIT
Fixed the bug with incorrect conversion to milliseconds according to Prasad19sara's comment.
A shorthand of the previous solutions is
var myDate = +new Date("2012-02-10T13:19:11+0000");
It does an on the fly type conversion and directly outputs date in millisecond format.
Another way is also using parse method of Date util which only outputs EPOCH time in milliseconds.
var myDate = Date.parse("2012-02-10T13:19:11+0000");
Another option as of 2017 is to use Date.parse(). MDN's documentation points out, however, that it is unreliable prior to ES5.
var date = new Date(); // today's date and time in ISO format
var myDate = Date.parse(date);
See the fiddle for more details.
Yes, you can do this in a single line
let ms = Date.parse('2019-05-15 07:11:10.673Z');
console.log(ms);//1557904270673
Another possible solution is to compare current date with January 1, 1970, you can get January 1, 1970 by new Date(0);
var date = new Date();
var myDate= date - new Date(0);
Another solution could be to use Number object parser like this:
let result = Number(new Date("2012-02-10T13:19:11+0000"));
let resultWithGetTime = (new Date("2012-02-10T13:19:11+0000")).getTime();
console.log(result);
console.log(resultWithGetTime);
This converts to milliseconds just like getTime() on Date object
var date = new Date()
console.log(" Date in MS last three digit = "+ date.getMilliseconds())
console.log(" MS = "+ Date.now())
Using this we can get date in milliseconds
var date = new Date(date_string);
var milliseconds = date.getTime();
This worked for me!
if wants to convert UTC date to milliseconds
syntax : Date.UTC(year, month, ?day, ?hours, ?min, ?sec, ?milisec);
e.g :
date_in_mili = Date.UTC(2020, 07, 03, 03, 40, 40, 40);
console.log('miliseconds', date_in_mili);
In case if anyone wants to grab only the Time from a ISO Date, following will be helpful. I was searching for that and I couldn't find a question for it. So in case some one sees will be helpful.
let isoDate = '2020-09-28T15:27:15+05:30';
let result = isoDate.match(/\d\d:\d\d/);
console.log(result[0]);
The output will be the only the time from isoDate which is,
15:27

What the elegant way to convert date in string to Date object?

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.

javascript compare two dates and throw an alert

I have two dates in DD/MM/YYYY HH:MM:SS format ,i want to compare two dates and throw an
alert .
I tried the below code,but it is not working.
startdate = "14/12/2014 19:00:00";
enddate = "21/01/2015 19:00:00";
if(new Date(startdate) > new Date(enddate))
{
alert("End date cannot be less than start date");
}
You can create a Date using the following constructors:
new Date();
new Date(value);
new Date(dateString);
new Date(year, month[, date[, hour[, minutes[, seconds[, milliseconds]]]]]);
You have used the third of them, where the dateString is a
String value representing a date. The string should be in a format
recognized by the Date.parse() method (IETF-compliant RFC 2822
timestamps and also a version of ISO8601).
The string you have provided hasn't the correct format. Hence the corresponding date objects haven't been created.
I would prefer using the last constructor, since I wouldn't have to format correspondingly the strings.
var startDate = new Date(2014,12,14,19,0,0);
var endDate = new Date(2015,1,21,19,0,0);
I swapped the startDate with the endDate, in order we see the alert.
var endDate = new Date(2014,12,14,19,0,0);
var startDate = new Date(2015,1,21,19,0,0);
if(startDate > endDate)
{
alert("End date cannot be less than start date");
}

getTime() in AngularJS , error in new Date(date) in Java Script

$scope.notAvailableDayClick=function(val1,date){
console.log("day clcik")
var startDate=$filter('date')(date,'yyyy-MM-dd')
var endDate=new Date(startDate)
endDate.setMinutes(59)
endDate.setHours(23)
}
date is 2015-01-16
if I do this
new Date(date)
Thu Jan 15 2015 16:00:00 GMT-0800 (Pacific Standard Time)
So I have to go with AngularJS
var startDate=$filter('date')(date,'yyyy-MM-dd')
but now I need startDate.getTime(), error occur I think it takes it as a String
As per angular docs the filter returns a String in requested format. Date constructor accepts ISO8601 formats usually although some browsers support many formats as I remember. Probably your format yy-MM-dd is not supported.
I hope the variable date is a valid Date object, in that case why don't you use it instead of the formatted string you made with angular filter?
var endDate = new Date(date);
endDate.setMinutes(59);
endDate.setHours(23);
Also you have a Date constructor that accepts the format
new Date(year, month[, date[, hour[, minutes[, seconds[, milliseconds]]]]]);
So if what you have in hand is 2015-01-16 you can get midnight of that day with:
var startDate = "2015-01-16";
var year = parseInt(startDate.split('-')[0], 10);
var month = parseInt(startDate.split('-')[1], 10) - 1;
var year = parseInt(startDate.split('-')[2], 10);
var endDate = new Date(year, month, date, 23, 59);
Just use the original date to create endDate not the angular filtered version
var endDate=new Date(date);
endDate.setMinutes(59);
endDate.setHours(23);
Best option is to use ISO-String, because Google Chrome supports this format: MM-dd-yyyy. In Mozilla this format gives Invalid Date.
new Date('MM-dd-yyyy')
So using Iso-String in Angular, it can done as follows:
new Date($filter('date')(yourdDate,'yyyy-MM-ddTHH:mm:ss.sssZ'))

What is wrong with this javascript date difference calculate function?

Any idea why this function doesn't work properly in Internet Explorer?
function days_between(check_in, check_out)
{
var oneDay = 24*60*60*1000;
var firstDate = new Date(check_in);
var secondDate = new Date(check_out);
var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay));
return diffDays;
}
in internet explorer it shows NaN as result.
im calling this function in this date format
var check_in = "2012-02-09";
var check_out = "2012-02-12";
var range = days_between(check_in, check_out);
Regards
IE doesn't support Date.parse or passing "2012-02-09" (with ISO dates) to new Date, you need to parse it yourself and pass new Date( 2012, 1, 9 ) or use a Date.parse shim for ISO dates
The date format you're passing (yyyy-mm-dd) isn't supported by Date. See the note here that says it must be in a format parsable by parse. See here for acceptable parse formats: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/parse
You have problem in creating the Date Object
Date objects are created with the Date() constructor.
There are four ways of instantiating a date:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Most parameters above are optional. Not specifying, causes 0 to be passed in.
Once a Date object is created, a number of methods allow you to operate on it. Most methods allow you to get and set the year, month, day, hour, minute, second, and milliseconds of the object, using either local time or UTC (universal, or GMT) time.
All dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC) with a day containing 86,400,000 milliseconds.
Some examples of instantiating a date:
var today = new Date()
var d1 = new Date("October 13, 1975 11:13:00")
var d2 = new Date(79,5,24)
var d3 = new Date(79,5,24,11,33,0)
(Taken from http://www.w3schools.com/js/js_obj_date.asp)
You are giving the date arguments in an incorrect format. You can expect javascript to support these formats:
MM-dd-yyyy
yyyy/MM/dd
MM/dd/yyyy
MMMM dd, yyyy
MMM dd, yyyy
To fix your immediate problem, you can use replace() to format your arguments.
function days_between(check_in, check_out)
{
var firstDate = new Date(check_in.replace('-' , '/'));
var secondDate = new Date(check_out.replace('-' , '/'));
var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime()) / 86400000);
return diffDays;
}
And by the way, you can replace oneDay with a constant.

Categories