Create new Date/Time using separate Date and Time - javascript

I have a form set-up in such a way that I collect the dates from a different input box and time from a dif
var appointment_date = new Date();
var appointment_start = new Date("Mon Apr 24 2017 20:00:00 GMT-0400 (EDT)");
var appointment_end = new Date("Mon Apr 24 2017 21:30:00 GMT-0400 (EDT)");
console.log(appointment_date);
console.log(appointment_start);
console.log(appointment_end);
let selected_day = appointment_date.toString().split(' ').slice(0, 1).join(' '),
selected_date = appointment_date.toString().split(' ').slice(1, 2).join(' '),
selected_month = appointment_date.toString().split(' ').slice(2, 3).join(' '),
selected_year = appointment_date.toString().split(' ').slice(3, 4).join(' ');
console.log(selected_day);
console.log(selected_date);
console.log(selected_month);
console.log(selected_year);
console.log(appointment_start.toString().split(' ').slice(4, appointment_start.toString().length).join(' '));
console.log(new Date(selected_year, selected_month, selected_date, appointment_start.toString().split(' ').slice(4, appointment_start.toString().length).join(' ')));
ferent input field.
I tried converting my Date and Time to string; splitting them and then joining it with the other time but it's not giving me the proper time. Is there a better way to do this?
where this.state.appointment_date = new Date();
this.state.appointment_start = new Date();
this.state.appointment_end = new Date();
let selected_day = this.state.appointment_date.toString().split(' ').slice(0, 1).join(' '), // Day
selected_date = this.state.appointment_date.toString().split(' ').slice(1, 2).join(' '), // Date
selected_month = this.state.appointment_date.toString().split(' ').slice(2, 3).join(' '), // Month
selected_year = this.state.appointment_date.toString().split(' ').slice(3, 4).join(' '); // Year
console.log(this.state.appointment_start.setDate(selected_day)); //NaN (output)
console.log(this.state.appointment_start.toString().split(' ').slice(4, this.state.appointment_start.toString().length).join(' ')); // no output
console.log(this.state.appointment_end.toString().split(' ').slice(4, this.state.appointment_end.toString().length).join(' ')); //time
// I tried to create a new date using the above date:
console.log(new Date(selected_day, selected_month, selected_date, selected_year, this.state.appointment_start.toString().split(' ').slice(4, this.state.appointment_start.toString().length).join(' ')));
But I get invalid date for it. Not sure how to do it :/
This way I was trying to break it up and then combine it again to create the final date. But this seems like a really long approach for something which should be simpler
Expected Input/Output:
Input: dates in the same format as new Date()
Output: Take day, month and year from appointment_date and time from appointment_start and create a new date object

The correct syntax of Date is
new Date(year, month, day, hours, minutes, seconds, milliseconds);
so you mess the supplied params.
The selected_day in your case will produce the name of the day.

In your code:
var appointment_date = new Date();
var appointment_start = new Date("Mon Apr 24 2017 20:00:00 GMT-0400 (EDT)");
var appointment_end = new Date("Mon Apr 24 2017 21:30:00 GMT-0400 (EDT)");
You should not parse strings with the Date constructor (or Date.parse) as it's largely implementation dependent. The standard does not require a string in this format to be parsed correctly. If you want to create some test dates, use:
var appointment_start = new Date(2017, 3, 24, 20);
assuming that your time zone is -0400. The first part of your code can be rewritten as:
var appointment_date = new Date();
var appointment_start = new Date(2017, 3, 24, 20);
var appointment_end = new Date(2017, 3, 24, 21, 30);
console.log(appointment_date.toString());
console.log(appointment_start.toString());
console.log(appointment_end.toString());
var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
var selected_day = days[appointment_date.getDay()],
selected_date = appointment_date.getDate(),
selected_month = appointment_date.getMonth() + 1,
selected_year = appointment_date.getFullYear();
console.log(selected_day);
console.log(selected_date);
console.log(selected_month);
console.log(selected_year);
let selected_day = appointment_date.toString().split(' ').slice(0, 1).join(' '),
This depends on the output of Date.prototype.toString having a particular format, however ECMA-262 allows the format to be implementation dependent, so it may have a different format in different hosts. See Where can I find documentation on formatting a date in JavaScript?
Consider using a library, or write your own small formatter if you only have one format to support.
Where you have:
console.log(this.state.appointment_start.setDate(selected_day)); //NaN (output)
You are passing a value like "Tue" (or maybe something completely different) instead of a date, so the result is NaN.
In the last line you have:
console.log(new Date(selected_year, selected_month, selected_date,
appointment_start.toString().split(' ').slice(4,
appointment_start.toString().length).join(' ')));
Which attempts to build a Date by passing values for the first three parameters, but then tries to pass all the parts for the time as a single string. You need to pass all the parts as individual values. Also, months are zero indexed so you need to subtract 1.
But there is no need for such convoluted code, all the parts of the date are available using Date methods, see Where can I find documentation on formatting a date in JavaScript? as noted above.

Related

Easiest way to create a javascript date from "18th apr 2011" / "1st jun 1980" format

This works:
var myDateString = '19th sep 2015';
myDateString = myDateString.replace('st','');
myDateString = myDateString.replace('th','');
myDateString = myDateString.replace('nd','');
myDateString = myDateString.replace('rd','');
var date = new Date(myDateString);
But is there a cleaner way? Can I pass the date format (including the ordinal part) to the Date constuctor?
I wouldn't rely on it parsing correctly for all people - for instance, people in France might have their locale set to French (surprise) and that would fail to parse apr for instance, because for them it's avr.
Instead, parse it yourself:
var myDateString = '19th sep 2015';
var parts = myDateString.split(" ");
var date = parts[0].replace(/\D/g,''); // keep only numbers
var month = "janfebmaraprmayjunjulaugsepoctnovdec".indexOf(parts[1].toLowerCase())/3;
var year = parts[2];
var date = new Date(year, month, date);
// note because of how we got the month, it's already conveniently zero-based
Use Moment.js library and use your date string like this:
moment('19th sep 2015', 'Do MMMM YYYY').format("D MMMM YYYY")
Output:
"19 September 2015"
The easiest way is to use a library like moment.js or the date part of sugar.js.
To do this properly by hand is not fun.
Update
If you're in full control of the dates, just use ISO 8601 date format, which the constructor of Date understands in any browser.

converting date into timestamp

I have date like this 25. 02. 2014 18:48:21 and I'm trying to convert it into timestamp
var someDate = '25. 02. 2014 18:48:21';
var timestamp = new Date(someDate).getTime();
but it's returning NaN since I moved files to a new domain, what can be a problem?
'25. 02. 2014 18:48:21' is not a valid date format. You'll have to convert it with regex first, like that:
var someDate = '25. 02. 2014 18:48:21';
var converted = someDate.replace(/^(\d{2}\. )(\d{2}\. )(\d{4})/, '$3. $2$1');
// converted is in format: YYYY. MM. DD.
var timestamp = new Date(converted).getTime();
Running this within the console, creating a new date with that variable gives me Invalid Date. Trying switching around the 25. and 02. like so:
var someDate = '02. 25. 2014 18:48:21';
var timestamp = new Date(someDate).getTime(); // 1393372101000
The format should be "Month, Day, Year, Time".
Switching month and day will work. I also removed the dots.
var date = "25. 02. 2014 18:48:21";
new Date(date.replace(/(\d{2})\. (\d{2})\./, '$2 $1'))
// Tue Feb 25 2014 18:48:21 GMT+0100 (W. Europe Standard Time)
you can try something like below (if your string has always same format)
var someDate = '25. 02. 2014 18:48:21';
var arr = someDate.split(' ');
var time = arr[3].split(':');
var timeStamp = new Date(arr[2],arr[1].split('.')[0],arr[0].split('.')[0],time [0],time[1],time[2]).getTime();
It uses javascript date object constructor
var d = new Date(year, month, day, hour, minute, seconds);
which works across all browsers
function convertSomeDate(str){
var d= str.match(/\d+/g),
dA= [d[2], '-', d[1], '-', d[0], 'T', d[3], ':', d[4], ':', d[5], 'Z'].join('');
return +new Date(dA)
}
var someDate= '25. 02. 2014 18:48:21';
convertSomeDate(someDate)
/* returned value: (Number)
1393354101000
*/

Why doesn't this new Date work in javascript?

I'm trying to display a date with format "MMM. dd HH:mm:ss.nnn". It is rendering it incorrectly in IE and I have spent quite some time and I can't figure out why I can't get this to work.
I know that Date.UTC returns the number of miliseconds in a Date object since Jan 1, 1970. So,
var newDate = new Date(Date.UTC(year, month[, date[, hrs[, min[, sec[, ms]]]]])
newDate.toString("MMM. dd HH:mm:ss.")+row.timestamp.getMilliseconds();
will work.
Example:
var newDate = new Date(Date.UTC(1950, 10, 10, 10, 09, 09, 100));
row.timestamp_f = newDate.toString("MMM. dd HH:mm:ss."); // Output => Nov. 10 05:09:09.
But, I am interating this from a jquey.each function so the date string that I am working with is an ISO 8601: "2013-03-12T15:14:10.483". So, this is what I have in mind.
var numMilisecond = Date.parse(row.timestamp);
var newDate = new Date(numMilisecond);
row.timestamp_f = newDate.toString("MMM. dd HH:mm:ss."); // Output => Dec. 31 19:00:00.
row.timestamp is from a JSON response
{"timestamp":"2013-03-12T15:14:10.483" ...}
Why doesn't the code work? Date.parse should return the number of miliseconds since Jan 1, 1970 and then I create a new Date obj and then convert it to string just like the code in the first snipet. What am I doing wrong?
Thanks.
Date.toString shouldn't accept any arguments. If you want a true date-formatting solution, you'll need to use a plugin or roll your own.
var shortmonths = ['Jan','Feb','Mar','Apr',]; // remaining months are left as an exercise for the reader
row.timestamp_f = shortmonths[newDate.getMonth()]
+ ". "+newDate.getDate() + " "
+ newDate.toLocaleTimeString() + ".";

convert custom date string to date object

How can I convert a string representation of a date to a real javascript date object?
the date has the following format
E MMM dd HH:mm:ss Z yyyy
e.g.
Sat Jun 30 00:00:00 CEST 2012
Thanks in advance
EDIT:
My working solution is based on the accepted answer. To get it work in IE8, you have to replace the month part (e.g. Jun) with the months number (e.g. 5 for June, because January is 0)
Your date string can mostly be parsed as is but CEST isn't a valid time zone in ISO 8601, so you'll have to manually replace it with +0200.
A simple solution thus might be :
var str = "Sat Jun 30 00:00:00 CEST 2012";
str = str.replace(/CEST/, '+0200');
var date = new Date(str);
If you want to support other time zones defined by their names, you'll have to find their possible values and the relevant offset. You can register them in a map :
var replacements = {
"ACDT": "+1030",
"CEST": "+0200",
...
};
for (var key in replacements) str = str.replace(key, replacements[key]);
var date = new Date(str);
This might be a good list of time zone abbreviation.
You can use following code to convert string into datetime:
var sDate = "01/09/2013 01:10:59";
var dateArray = sDate.split('/');
var day = dateArray[1];
// Attention! JavaScript consider months in the range 0 - 11
var month = dateArray[0] - 1;
var year = dateArray[2].split(' ')[0];
var hour = (dateArray[2].split(' ')[1]).split(':')[0];
var minute = (dateArray[2].split(' ')[1]).split(':')[1];
var objDt = new Date(year, month, day, hour, minute);
alert(objDt);

Convert dd-mm-yyyy string to date

i am trying to convert a string in the format dd-mm-yyyy into a date object in JavaScript using the following:
var from = $("#datepicker").val();
var to = $("#datepickertwo").val();
var f = new Date(from);
var t = new Date(to);
("#datepicker").val() contains a date in the format dd-mm-yyyy.
When I do the following, I get "Invalid Date":
alert(f);
Is this because of the '-' symbol? How can I overcome this?
Split on "-"
Parse the string into the parts you need:
var from = $("#datepicker").val().split("-")
var f = new Date(from[2], from[1] - 1, from[0])
Use regex
var date = new Date("15-05-2018".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3"))
Why not use regex?
Because you know you'll be working on a string made up of three parts, separated by hyphens.
However, if you were looking for that same string within another string, regex would be the way to go.
Reuse
Because you're doing this more than once in your sample code, and maybe elsewhere in your code base, wrap it up in a function:
function toDate(dateStr) {
var parts = dateStr.split("-")
return new Date(parts[2], parts[1] - 1, parts[0])
}
Using as:
var from = $("#datepicker").val()
var to = $("#datepickertwo").val()
var f = toDate(from)
var t = toDate(to)
Or if you don't mind jQuery in your function:
function toDate(selector) {
var from = $(selector).val().split("-")
return new Date(from[2], from[1] - 1, from[0])
}
Using as:
var f = toDate("#datepicker")
var t = toDate("#datepickertwo")
Modern JavaScript
If you're able to use more modern JS, array destructuring is a nice touch also:
const toDate = (dateStr) => {
const [day, month, year] = dateStr.split("-")
return new Date(year, month - 1, day)
}
regular expression example:
new Date( "13-01-2011".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3") );
Another possibility:
var from = "10-11-2011";
var numbers = from.match(/\d+/g);
var date = new Date(numbers[2], numbers[0]-1, numbers[1]);
Match the digits and reorder them
Using moment.js example:
var from = '11-04-2017' // OR $("#datepicker").val();
var milliseconds = moment(from, "DD-MM-YYYY").format('x');
var f = new Date(milliseconds)
Use this format: myDate = new Date('2011-01-03'); // Mon Jan 03 2011 00:00:00
var from = $("#datepicker").val();
var f = $.datepicker.parseDate("d-m-Y", from);
You can also write a date inside the parentheses of the Date() object, like these:
new Date("Month dd, yyyy hh:mm:ss")
new Date("Month dd, yyyy")
new Date(yyyy,mm,dd,hh,mm,ss)
new Date(yyyy,mm,dd)
new Date(milliseconds)
In my case
new Date("20151102034013".replace(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/, "$1-$2-$3T$4:$5:$6"))
Result: Mon Nov 02 2015 04:40:13 GMT+0100 (CET)
then I use .getTime() to work with milliseconds
The accepted answer kinda has a bug
var from = $("#datepicker").val().split("-")
var f = new Date(from[2], from[1] - 1, from[0])
Consider if the datepicker contains "77-78-7980" which is obviously not a valid date. This would result in:
var f = new Date(7980, 77, 77);
=> Date 7986-08-15T22:00:00.000Z
Which is probably not the desired result.
The reason for this is explained on the MDN site:
Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1).
A better way to solve the problem is:
const stringToDate = function(dateString) {
const [dd, mm, yyyy] = dateString.split("-");
return new Date(`${yyyy}-${mm}-${dd}`);
};
console.log(stringToDate('04-04-2019'));
// Date 2019-04-04T00:00:00.000Z
console.log(stringToDate('77-78-7980'));
// Invalid Date
This gives you the possibility to handle invalid input.
For example:
const date = stringToDate("77-78-7980");
if (date === "Invalid Date" || isNaN(date)) {
console.log("It's all gone bad");
} else {
// Do something with your valid date here
}
You can use an external library to help you out.
http://www.mattkruse.com/javascript/date/source.html
getDateFromFormat(val,format);
Also see this: Parse DateTime string in JavaScript
You can just:
var f = new Date(from.split('-').reverse().join('/'));
let dateString = '13-02-2021' //date string in dd-mm-yyyy format
let dateArray = dateString.split("-");
//dateArray[2] equals to 2021
//dateArray[1] equals to 02
//dateArray[0] equals to 13
// using template literals below
let dateObj = new Date(`${dateArray[2]}-${dateArray[1]}-${dateArray[0]}`);
// dateObj equals to Sat Feb 13 2021 05:30:00 GMT+0530 (India Standard Time)
//I'm from India so its showing GMT+0530
P.S : Always refer docs for basics, MDN or DevDocs
Take a look at Datejs for all those petty date related issues.. You could solve this by parseDate function too
You could use a Regexp.
var result = /^(\d{2})-(\d{2})-(\d{4})$/.exec($("#datepicker").val());
if (result) {
from = new Date(
parseInt(result[3], 10),
parseInt(result[2], 10) - 1,
parseInt(result[1], 10)
);
}
new Date().toLocaleDateString();
simple as that, just pass your date to js Date Object

Categories