How do I combine these variables in my code :
var date1 = "13:38";
var date2 = "2019-05-14T00:00:00"
I want to add the time from date1 to date2, so the result should be "2019-05-14T13:38:00"
It's not clear what you are trying to do. If the date and time timestamp always has a time of 00:00:00 and you just want to update the time component, you can do that as a string.
Since "2019-05-14T00:00:00" has no offset, it should be parsed as local, so will represent a different moment in time for each different location with a different offset. If it should be parsed as UTC, please make that clear in the OP. It's fairly easy to go either way, you just have to make it clear how it should be treated.
I've allowed for an optional seconds component.
var date1 = "13:38";
var date2 = "2019-05-14T00:00:00";
let [h, m, s] = date1.split(':');
console.log(date2.substring(0,11) + h + ':' + m + ':' + (s||'00'));
However, if the date and time timestamp also has a non–zero time component and you need to add time, a Date object can make life easier:
// Parse ISO 8601 timestamp in YYYY-MM-DDTHH:mm:ss format
// Assumes no offset, parses as local
function parseDateTime(dt) {
let [Y, M, D, h, m, s] = dt.split(/\D/);
return new Date(Y, M-1, D, h, m, s);
}
// Add time in hh:mm[:ss] format to a date
// Returns a new date, doesn't modify date passed in
function addTime(date, time) {
let [h, m, s] = time.split(/\D/);
let d = new Date(+date);
d.setHours(d.getHours() + +h,
d.getMinutes() + +m,
d.getSeconds() + +m);
return d;
}
let date1 = "13:38";
let date2 = "2019-05-14T03:42:28";
let d = parseDateTime(date2);
let e = addTime(d, date1);
// UTC timestamp in ISO 8601 format
console.log(e.toISOString());
Note that in the second example, the displayed value uses the built–in toISOString method that shifts the offset to UTC (+0). If you want the ISO format but in the local timezone, then you can manually format the string. There are lots of questions and answers on how to do that.
There are also numerous libraries that can help. Since the Date object hasn't changed much in over 20 years, any that have been around a while should be OK.
You will have to parse the first timesting and construct a new date object from it. You should construct a UTC object and pass that into the constructor.
For the second datestring, you will need to add the Zulu token to the end to donate a UTC time and make it ISO 8601 compliant.
After you have your two date objects, update the minutes and hours of the second date object, because that one already stores date information.
const date1 = "13:38";
const date2 = "2019-05-14T00:00:00";
const dateObj1 = (tokens =>
new Date(Date.UTC(0, 0, 0, tokens[0], tokens[1])))
(date1.split(':'));
const dateObj2 = new Date(date2 + 'Z');
dateObj2.setUTCMinutes(dateObj2.getUTCMinutes() + dateObj1.getUTCMinutes());
dateObj2.setUTCHours(dateObj2.getUTCHours() + dateObj1.getUTCHours());
console.log(dateObj2.toISOString().substring(0, 19)); // 2019-05-14T13:38:00
If you want to do this in Moment, you can try the following:
const date1 = "13:38";
const date2 = "2019-05-14T00:00:00";
const moment1 = moment.utc(date1, 'HH:mm');
const moment2 = moment.utc(date2)
.add(moment1.minutes(), 'minutes')
.add(moment1.hours(), 'hours')
console.log(moment2.format('YYYY-MM-DDTHH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
Related
I'm trying to compare given date with current date, It is working fine for Indian timezone but other time zones getting one day off. I have went through similar type of issues and there suggestions are like convert UTC string. After converting UTC string getting correct date while console but when comparing not get correct result.
Here my given date in the format like 'YYYY-MM-DD'.
The initial comparison was like below, and this will work fine for Indian timezone.
const datestring = '2019-05-06';
const q = new Date();
const m = q.getMonth();
const d = q.getDate();
const y = q.getFullYear();
const currentDate = new Date(y, m, d);
const givenDate = new Date(datestring);
if (currentDate <= givenDate) {
return null;
} else {
return {
'currentDateChecker': true
};
}
}
The above one will work fine for Indian time zone and for some other time zone apart from Indian time zone, it is giving one day less.
But after converting to UTC like:
const givenDate = new Date(datestring).toUTCString();
Now this will give correct date but for comparing purpose I have converted both current date also to UTC string, by that time result is not coming as expected. I know there are number of articles existed related to this but not getting proper way so only posting this question.
The difficulty is that new Date() will create a date in YOUR timezone. For me, since I'm SAST (+2 hours), if I say new Date(2019, 4, 6) I will get the UTC datetime 5 May 22:00 2019. This makes it difficult to compare dates, since someone in India who wanted to compare "6 May 2019" will actually get a UTC date 6 May 2019, and that won't equal 5 May 2019.
Instead use Date.UTC(year, month, day) - an epoch time is number of milliseconds since 2970, Jan 1st in UTC.
const today = new Date()
const todayYear = today.getFullYear()
const todayMonth = today.getMonth()
const todayDay = today.getDate()
const todayUtc = Date.UTC(todayYear, todayMonth, todayDay)
const dateString = 'yyyy-mm-dd'
const dateArr = dateString.split('-')
const dateUtc = Date.UTC(dateArr[0], dateArr[1], dateArr[2])
if (todayUtc === dateUtc) {
// ...
}
You can use getTime to do the comparaison:
// ...
const currentDate = new Date(y, m, d).getTime();
const givenDate = new Date(datestring).getTime();
if (currentDate <= givenDate) {
return null;
} else {
return {
'currentDateChecker': true
};
}
I simply need the number of seconds from the midnight of the present day.
It's a labyrinth of JS Date methods I can't untangle from.
I already searched for an off-the-shelf snippet. I tried this but it returns local time, not UTC:
let date = new Date(),
d = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(),
date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(),
date.getUTCSeconds())),
e = new Date(d),
secsSinceMidnight = Math.floor((e - d.setUTCHours(0,0,0,0)) / 1000);
I think you had the right idea, but got lost in the implementation. Your assignment to d is just a very long winded way of creating a copy of date that is equivalent to the assignment to e.
To get "seconds from UTC midnight", create a Date for now and subtract it from a copy that has the UTC hours set to 00:00:00.000.
function secsSinceUTCMidnight() {
var d = new Date();
var c = new Date(+d);
return (d - c.setUTCHours(0,0,0,0)) / 1000;
}
console.log('Seconds since UTC midnight: ' +
secsSinceUTCMidnight().toLocaleString() + '\n' + new Date().toISOString());
This question already has answers here:
Convert dd-mm-yyyy string to date
(15 answers)
Closed 8 months ago.
How to convert a date in format 23/10/2015 into a
JavaScript Date format:
Fri Oct 23 2015 15:24:53 GMT+0530 (India Standard Time)
MM/DD/YYYY format
If you have the MM/DD/YYYY format which is default for JavaScript, you can simply pass your string to Date(string) constructor. It will parse it for you.
var dateString = "10/23/2015"; // Oct 23
var dateObject = new Date(dateString);
document.body.innerHTML = dateObject.toString();
DD/MM/YYYY format - manually
If you work with this format, then you can split the date in order to get day, month and year separately and then use it in another constructor - Date(year, month, day):
var dateString = "23/10/2015"; // Oct 23
var dateParts = dateString.split("/");
// month is 0-based, that's why we need dataParts[1] - 1
var dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]);
document.body.innerHTML = dateObject.toString();
For more information, you can read article about Date at Mozilla Developer Network.
DD/MM/YYYY - using moment.js library
Alternatively, you can use moment.js library, which is probably the most popular library to parse and operate with date and time in JavaScript:
var dateString = "23/10/2015"; // Oct 23
var dateMomentObject = moment(dateString, "DD/MM/YYYY"); // 1st argument - string, 2nd argument - format
var dateObject = dateMomentObject.toDate(); // convert moment.js object to Date object
document.body.innerHTML = dateObject.toString();
<script src="https://momentjs.com/downloads/moment.min.js"></script>
In all three examples dateObject variable contains an object of type Date, which represents a moment in time and can be further converted to any string format.
Here's one I prepared earlier...
convertToDate(dateString) {
// Convert a "dd/MM/yyyy" string into a Date object
let d = dateString.split("/");
let dat = new Date(d[2] + '/' + d[1] + '/' + d[0]);
return dat;
}
var dateString = "23/10/2015"; // Oct 23
var newData = dateString.replace(/(\d+[/])(\d+[/])/, '$2$1');
var data = new Date(newData);
document.body.innerHTML = date.toString();ere
While most responses were tied to splitting strings or using native date methods, the two closely-related ones using RegEx (i.e., answer by [drgol] and comment by [Tomás Hugo Almeida]) are both instructive about the use of capturing groups. Their succinctness also helps illustrate the value of capturing and distinguishing that from matching - two related concepts that can confuse new RegEx users. This code block consolidates their 2 answers but see originals above: const origDate = '23/07/2020'; const newDate = origDate.replace(/(\d+[/])(\d+[/])/, '$2$1'); // newDate = '07/23/2020';
I found the default JS date formatting didn't work.
So I used toLocaleString with options
const event = new Date();
const options = { dateStyle: 'short' };
const date = event.toLocaleString('en', options);
to get: DD/MM/YYYY format
See docs for more formatting options: https://www.w3schools.com/jsref/jsref_tolocalestring.asp
Parsing a string to create another string that is then parsed by the built–in parser is not an efficient strategy, particularly when neither string is in a format supported by ECMA-262.
A more efficient strategy is to parse the string once and give the parts directly to the constructor, avoiding the second parse, e.g.
const parseDMY = s => {
let [d, m, y] = s.split(/\D/);
return new Date(y, m-1, d);
};
console.log(parseDMY('23/10/2015').toString());
Date.parse only supports the formats produced by:
Date.protoype.toString
Date.protoype.toISOString
Date.protoype.toUTCString
Parsing of any other format (including m/d/y) is implementation dependent.
Here is a way to transform a date string with a time of day to a date object. For example to convert "20/10/2020 18:11:25" ("DD/MM/YYYY HH:MI:SS" format) to a date object
function newUYDate(pDate) {
let dd = pDate.split("/")[0].padStart(2, "0");
let mm = pDate.split("/")[1].padStart(2, "0");
let yyyy = pDate.split("/")[2].split(" ")[0];
let hh = pDate.split("/")[2].split(" ")[1].split(":")[0].padStart(2, "0");
let mi = pDate.split("/")[2].split(" ")[1].split(":")[1].padStart(2, "0");
let secs = pDate.split("/")[2].split(" ")[1].split(":")[2].padStart(2, "0");
mm = (parseInt(mm) - 1).toString(); // January is 0
return new Date(yyyy, mm, dd, hh, mi, secs);
}
you can use this short function
// dateString: "15/06/2021"
const stringToDate = (dateString) => {
const [day, month, year] = dateString.split('/');
return new Date([month, day, year].join('/'));
};
document.body.innerHTML = stringToDate("15/06/2021").toString();
var date = new Date("enter your date");//2018-01-17 14:58:29.013
Just one line is enough no need to do any kind of split, join, etc.:
$scope.ssdate=date.toLocaleDateString();// mm/dd/yyyy format
<!DOCTYPE html>
<script>
dateString = "23/10/2015"; //23 Oct 2015
d = dateString.split("/");
x = d[1] + "/" + d[0] + "/" + d[2]; //"10/23/2015"
y = d[2] + "/" + d[1] + "/" + d[0]; //"2015/10/23"
alert(
new Date(x) + "\n\n" +
new Date(y) + "\n\n" +
new Date(dateString) + "\n" +
"");
</script>
I have two variables, date & time...
var date = "2012-12-05";
var time = "18:00";
How can I format this into a UTC formatted date. This is so I can use it within the Facebook API..
Facebook states I need it in this format:
Precise-time (e.g., '2012-07-04T19:00:00-0700'): events that start at a particular point in time, in a specific offset from UTC. This is the way new Facebook events keep track of time, and allows users to view events in different timezones.
Any help would be much appreciated.. Thanks!
This format is called ISO 8601
Do you know what timezone you are in? If you do, you can do like this:
var datetime = date + 'T' + time + ":00+0000';
if the timezone is +0.
if not, then:
var d = new Date()
var n = d.getTimezoneOffset();
var timeZone = Math.floor( Math.abs( n/60 ) );
var timeZoneString = (d.getTimezoneOffset() < 0 ? '-' : '+' ) + ( timeZone < 10 ? '0' + timeZone : timeZone ) + '00';
var datetime = date + 'T' + time + ':00' + timeZoneString;
Here is a fiddle: http://jsfiddle.net/ajySr/
Try the following:
var date = new Date(2012, 12, 5, 18, 0, 0, 0);
var date_utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
The Date function can be used the following ways:
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
This was taken from a related post here: How do you convert a JavaScript date to UTC?
To find out more, please refer to: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
The timestamp I get from a server's SOAP response is formatted in European Notation and in GMT time (ex: 08/07/2010 11:22:00 AM). I want to convert it to local time and change the formatting to (MM/DD/2010 HH:MM:SS AM/PM).
I know about the JavaScript Date object but can't figure out the logic of how to do the conversion. Can anyone help me?
Do you really need date objects for this? If all you're doing is switching the first two parts of a string of that exact format,
var pieces = str.split('/');
str = pieces[1] + '/' + pieces[0] + '/' + pieces[2];
Parse dates using:
Date.parse("08/07/2010 11:22:00 AM");
To convert the GMT date to local date (one on the browser or js useragent) use the following function:
function getLocalTime(gmt) {
var min = gmt.getTime() / 1000 / 60; // convert gmt date to minutes
var localNow = new Date().getTimezoneOffset(); // get the timezone
// offset in minutes
var localTime = min - localNow; // get the local time
return new Date(localTime * 1000 * 60); // convert it into a date
}
var dt = new Date(Date.parse("08/07/2010 11:22:00 AM"));
var localDate = getLocalTime(dt);
Next is date formatting, which is quite simple. Call the following functions on your newly obtained (local) date:
localDate.getXXX(); // where XXX is Hour, Minutes, etc.
Note: Tested in FF. Tweak as required in other browsers :)
I know this is a year old and has an accepted answer. Just in case someone comes around looking...
You can append the timezone information to the formatted string and create a date object to get what you want.
var x = "08/07/2010 11:22:00 AM".split('/');
var d = new Date(x[1] + '/' + x[0] + '/' + x[2] + " GMT");
jsfiddle
Just to make sure I understand what you wanted, I ran the accpeted answer along with this, both return the same result.
function switchFormat(dateString) {
var a = dateString.split('/'),
b;
b = a[0];
a[0] = a[1];
a[1] = b;
return a.join('/');
}
Edited
Try it here
var serverTimestamp = storArray[a][0];
var pieces = serverTimestamp.split('/');
storArray[a][0] = pieces[1] + '/' + pieces[0] + '/' + pieces[2];
var gmt = new Date(storArray[a][0]);
var localTime = gmt.getTime() - (gmt.getTimezoneOffset() * 60000); // convert gmt date to minutes
var localDate = new Date(localTime); // convert it into a date
Step 1 you are getting date from input type date like below
like 2021-08-18 as string
then
var formatted date = date.split('-')[2]+"/"+date.split('-')1+"/"+date.split('-')[0])
result will be 18/08/2021