Convert Date and Time into a UTC formatted Date - Javascript - javascript

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

Related

Add date and time string variables together

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>

How to convert datetime to UTC+1 in JavaScript

We have created a function in node-red, where we cleaning a datetime received from the metadata of a sensor. Unfortunately, the timezone fetched is one hour behind, and therefore a "wrong datetime" is sent. We need to convert this datetime to UTC+1 ('Europe/Berlin'). The function is in JavaScript, and in my knowledge we can't use third party libraries like moment etc.
Hopefully, someone here can help us. Thanks in advance!
This is what we have done so far:
var time = msg.metadata.time;
var datetime = new Date().toLocaleString();
var timedate = new Date(time);
var y = timedate.getFullYear().toString();
var m = (timedate.getMonth() + 1).toString();
var d = timedate.getDate().toString();
(d.length == 1) && (d = '0' + d);
(m.length == 1) && (m = '0' + m);
timedate.setHours(timedate.getHours() + 1)
var h = timedate.getHours().toString();
var min = timedate.getMinutes().toString();
var s = timedate.getSeconds().toString();
(h.length == 1) && (h = '0' + h);
(min.length == 1) && (min = '0' + min);
(s.length == 1) && (s = '0' + s);
var date = y+'-'+m+'-'+d
var time = h + ":" + min + ":" + s;
var timeDate = date+' '+time;
I would consider using Date.toLocaleString() for date/time conversion.
Now Moment.js will be better if you can use it, but you can convert times like below.
Remember you must consider DST changes and these are hard to account for using your own code (the exact dates of DST switchover change from year to year).
For example, Berlin uses CET (UTC+1) from late October to late March and CEST (UTC+2) from late March to late October.
Why am I using a locale of "sv", this is because it will essentially give us an ISO 8601 timestamp. Of course for converting to text you can use any locale.
I've added a getUTCOffsetMinutes function that will return the UTC offset in minutes for a given UTC time and timezone.
A list of IANA timezones is here: timezone list
const time = 1559347200000; // 2019-06-01T00:00:00Z
console.log("UTC time 1:", new Date(time).toISOString());
console.log("Berlin time 1 (ISO):", new Date(time).toLocaleString("sv", { timeZone: "Europe/Berlin"}));
console.log("Berlin time 1 (de):", new Date(time).toLocaleString("de", { timeZone: "Europe/Berlin"}));
const time2 = 1575158400000; // 2019-12-01T00:00:00Z
console.log("UTC time 2:", new Date(time2).toISOString());
console.log("Berlin time 2 (ISO):", new Date(time2).toLocaleString("sv", { timeZone: "Europe/Berlin"}));
console.log("Berlin time 2 (de):", new Date(time2).toLocaleString("de", { timeZone: "Europe/Berlin"}));
// You can also get the UTC offset using a simple enough function:
// Again, this will take into account DST
function getUTCOffsetMinutes(unixDate, tz) {
const localTimeISO = new Date(unixDate).toLocaleString("sv", {timeZone: tz}).replace(" ", "T") + "Z";
return (new Date(localTimeISO).getTime() - unixDate) / 60000; // Milliseconds to minutes.
}
console.log("UTC offset minutes (June/Berlin):", getUTCOffsetMinutes(time, "Europe/Berlin"));
console.log("UTC offset minutes (June/LA):", getUTCOffsetMinutes(time, "America/Los_Angeles"));
console.log("UTC offset minutes (June/Sydney):",getUTCOffsetMinutes(time, "Australia/Sydney"));
console.log("UTC offset minutes (December/Berlin):", getUTCOffsetMinutes(time2, "Europe/Berlin"));
console.log("UTC offset minutes (December/LA):", getUTCOffsetMinutes(time2, "America/Los_Angeles"));
console.log("UTC offset minutes (December/Sydney):", getUTCOffsetMinutes(time2, "Australia/Sydney"));
I use this function I made, i think it may help you:
function formatDateToOffset(date, timeOffset){
var dateInfo, timeInfo;
// change date's hours based on offset
date.setHours(date.getHours() + (timeOffset || 0))
// place it the way you want to format
dateInfo = [date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()]
timeInfo = [date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()];
// return the string formatted date
return dateInfo.join("-") + " " + timeInfo.join(":");
}
console.log(formatDateToOffset(new Date(), 1))

I calculated to get the first day of the month but go the last

I start by getting the date of the beginning of month:
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
Then I convert it to ISO:
firstDay = firstDay.toISOString();
Why did I get 2019-05-31 as the first day instead of 2019-06-01?
You could use a simple regex to format the string using replace:
/(\d{4})-(\d{2})-(\d{2}).+/
// Set the inital date to a UTC date
var date = new Date(new Date().toLocaleString("en-US", {timeZone: "UTC"}))
// Update the day without affecting the month/day when using toISOString()
date.setDate(1)
// Format the date
let formatted = date.toISOString().replace(/(\d{4})-(\d{2})-(\d{2}).+/, '$3-$2-$1')
console.log(formatted)
The default javascript date uses your local timezone, by converting it to something else you can end up with a different date.
You can do it
var firstDay = new Date().toISOString().slice(0, 8) + '01';
console.log(firstDay);
The date object in javascript can be somewhat tricky. When you create a date, it is created in your local timezone, but toISOString() gets the date according to UTC. The following should convert the date to ISO but keep it in your own time zone.
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var day = 0;
if (firstDay.getDate() < 10) {
day = '0' + firstDay.getDate();
}
var month = 0;
if ((firstDay.getMonth() + 1) < 10) {
//months are zero indexed, so we have to add 1
month = '0' + (firstDay.getMonth() + 1);
}
firstDay = firstDay.getFullYear() + '-' + month + '-' + day;
console.log(firstDay);

Get Seconds from midnight UTC

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());

javascript - get next day of a string

I've a var example = "05-10-1983"
How I can get the "next day" of the string example?
I've try to use Date object...but nothing...
This would do it for simple scenarios like the one you have:
var example = '05-10-1983';
var date = new Date();
var parts = example.split('-');
date.setFullYear(parts[2], parts[0]-1, parts[1]); // year, month (0-based), day
date.setTime(date.getTime() + 86400000);
alert(date);
Essentially, we create an empty Date object and set the year, month, and date with the setFullYear() function. We then grab the timestamp from that date using getTime() and add 1 day (86400000 milliseconds) to it and set it back to the date using the setTime() function.
If you need something more complicated than this, like support for different formats and stuff like that, you should take a look at the datejs library which does quite a bit of work for you.
You can do the following:
var nextDay;
var example = "05-10-1983";
nextDay = new Date(example);
nextDay.setDate(nextDay.getDate() + 1);
#getDate/#setDate gets/sets the current day of the month (1-31).
After the above is run, nextDay will be set to whatever tomorrow's date is. This will also rollover to the next month / year if it's the end of the month, and even handle leap years. :)
new Date(+new Date('05-10-1983'.replace(/-/g,'/')) + 24*60*60*1000)
The problem with the +86400000 approach is the potential for error when crossing a daylight savings time barrier.
For example, I'm on EST.
If I do this:
var d = new Date("11/04/2012 00:00:00");
var e = new Date(d.getTime() + 86400000);
e is going to be 11/4/2012 23:00:00
If you then extract just the date portion, you get the wrong value. I recently hit upon this issue while writing a calendar control.
this will do it better (and with a flexible offset which will let you do more than 1 day in the future):
function getTomorrow(d,offset) {
if (!offset) { offset = 1 }
return new Date(new Date().setDate(d.getDate() + offset));
}
So
var d = new Date("11/04/2012 00:00:00");
var e = new Date(d.getTime() + 86400000);
doesn't work because of daylight saving barriers. I ran into the same problem. I ended up doing something like this:
function next_day(date) {
var e = new Date(date.getTime() + 24 * 60 * 60 * 1000);
if e.getHours() != date.getHours() {
e = new Date(e.getTime() + (e.getHours() - date.getHours()) * 60 * 60 * 1000)
}
return e;
}
You can use framework called php.js. Google for it. This includes the advanced date functions and more
You can find out day index by getDay() function and create an array of days strings in following manner-
day = new Date(YourDate);
var dayArray = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
day = dayArray[day.getDay()+1];
There are leap seconds, leap days, DST, etc., so this can be a tricky problem to solve in all cases.
In my opinion, the best way to address this (without a date library) is to take advantage of the Date constructor overflow feature[1]:
main();
function main() {
var date = uniqueDateParse( '05-10-1983' );
var newDate = nextDay( date );
print( date );
print( newDate );
}
function uniqueDateParse( string ) {
var stringArray = string.split( '-', 3 );
var month = stringArray[ 0 ],
day = stringArray[ 1 ],
year = stringArray[ 2 ];
// Per ISO 8601[2], using Pacific Daylight Time[3].
var dateString = year + '-' + month + '-' + day + 'T00:00:00-07:00';
return new Date( dateString );
}
function nextDay( date ) {
return new Date( date.getFullYear()
, date.getMonth()
, date.getDate() + 1 );
}
function print( object ) {
console.log( object );
}
Links
[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Parameters
[2] http://www.w3.org/TR/NOTE-datetime
[3] http://www.timeanddate.com/time/zones/pdt

Categories