I'm trying to convert date/time into local time, instead of UTC.
I'm getting the date and time from an API and this is giving it on UTC. So I need to convert it from UTC to local time, because after 6:00 pm it displays the date for the next day.
I've tried moment and 'toString', and it works on localhost but if I host it it still gives me UTC
let dateTesting = subscription.current_period_started_at._
let dateTesting2 = moment.utc(dateTesting).local().format('MM-DD- YYYY HH:mm:ss')
let dateTesting3 = dateTesting.toString("MM/dd/yyyy HH:mm")
console.log('- now in UTC', dateTesting)
console.log('dateTesting2 -------', dateTesting2)
console.log('without moment', dateTesting3)
The result from the code above is:
now in UTC 2019-01-09T17:16:25Z
dateTesting2 ------- 01-09-2019 17:16:25
without moment 2019-01-09T17:16:25Z
I want the date to appear the same as in my computer (-6 hours)
You could force the issue with something like
`moment.utc(dateTesting).local().format('MM-DD-YYYY HH:mm:ss').subtract(6, 'hours)`
If you know your TIME_ZONE (sure), you can use:
const TIME_ZONE = -6;
const now = new Date(dateTesting);
now.setHours(now.getHours + TIME_ZONE) // or now.setMinutes(now.getMinutes()+ 60 * TIME_ZONE))
// because sometime TIME_ZONE is not `int`, example 4.5, 5.5, v.v,
//use with variable now, it's time same your time
If you run anywhere, you can get UTC time and convert it to your time, or you can use getTimezoneOffset:
const TIME_OFFSET = 360; // TIME_OFFSET = TIME_ZONE * 60
const now = new Date(time_of_any_where);
const thatOffset = now.getTimezoneOffset();
now.setMinutes(now.getMinutes+ thatOffset - TIME_OFFSET)
// Do something with `now`
Related
I am using https://openweathermap.org/current api and i want to get current date and time of the target city, I am getting timezone (shift in seconds from UTC) value from api, so how can i get the current time using this timezone offset value.
Lets suppose I have received this below timezone offset value from api
const timezone = -14400
const timezone = -14400 //needs to be converted in minutes
const timezoneInMinutes = timezone / 60;
const currTime = moment().utcOffset(timezoneInMinutes).format("h:mm A");
// 10:10 PM
https://momentjs.com/docs/#/parsing/unix-timestamp/
https://momentjs.com/docs/#/manipulating/add/
const dt = 1593674356; // unix timestamp in seconds
const timezone = 3600; // zone in seconds
// moment.unix - Unix Timestamp (seconds)
const dateTime = moment.unix(dt).utc().add(timezone, 's');
console.log(dateTime);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
I have UTC timeZone Date which I want to convert CST or DST based on whether DST is applied in the same city or not.
Since my browser is not based on same city so local time is no use of it.
example: my user is based on India but they will see data for NewYork Date also
I have a server based on NewYork so using SSR I can get date of the server but its always showing in CST how I can change the date into DST?
try this code. it might help you.
let d = new Date()
let utc = d.getTime() + (d.getTimezoneOffset() * 60000)
let today = new Date(utc - (3600000 * 6)) // 6 is for cst timezone. we can change this to get other timezome . this is offset
let dd = today.getDate()
let mm = today.getMonth()+1
let yy = today.getFullYear()
let hh = today.getHours()
let i = today.getMinutes()
let sec = today.getSeconds()
hh = hh.toString().length<2?("0"+hh):hh
mm = mm.toString().length<2?("0"+mm):mm
i = i.toString().length<2?"0"+i:i
sec = sec.toString().length<2?"0"+sec:sec
let timestamp = dd+'/'+mm+'/'+yy+' '+hh+':'+i+':'+sec
console.log('timestamp ',timestamp)
You can use Date.toLocaleString() to convert a UTC date to a specific timezone. This will honour the local DST rules and is native JavaScript code (no libraries required!)
So, if we have a list of UTC dates, we can convert to a specific timezone. I've created a list of UTC dates and timezones and formatted the dates for that timezone and date.
You can select a different display locale of course, for example if you have Indian clients you could use "en-in" or whichever you decide is the best display locale.
You should be able to do any timezone conversion either on the server side or (preferably) on the client side. If you send all dates to the client in UTC format (e.g. YYYY-MM-DDTHH:mm:ssZ) you can convert to the client timezone in the client code.
const displayLocale = "en-us"; // Set this to en-gb, en-in etc..
const uctDateList = [ new Date("2019-06-01T12:00:00Z"), new Date("2019-12-01T12:00:00Z")];
const timeZoneList = ['America/New_York', 'America/Los_Angeles', 'Asia/Kolkata'];
uctDateList.forEach(utcDate => {
console.log("\nServer Time: ", utcDate.toISOString());
timeZoneList.forEach(timeZone => {
console.log(`Time in timezone (${timeZone}):`, utcDate.toLocaleString(displayLocale, { timeZone }));
})
});
Well I have a time string like "06:00:00+00" and "06:00:00+01" and I wish to convert those to a literal to show the current offset to "utc zero".
The code I tried:
const v="06:00:00+00"
const fmt = "hh:mm:ss Z"
const m = moment(v, fmt).diff(moment(v, fmt).startOf('day'));
console.log(m);
console.log(m/(3600*1000));
However this logs "8 hours". - as if it uses my local timezone. - Trying to remove the time zone parameter fmt = "hh:mm:ss" makes it just ignore the time zone.
So how can I achieve this? (And yes this would mean the integer could be negative, if utc is not yet in the specified date).
A solution with core JS to compare to UTC:
function getTimeDiff(timeString) {
let curDate = new Date().toISOString().split('T')[0];
return (new Date(`${curDate}T${timeString}00`).getTime() - new Date(`${curDate}T00:00:00Z`).getTime())/(3600 * 1000);
}
console.log(getTimeDiff("06:00:00+01"));
console.log(getTimeDiff("06:00:00-07"));
console.log(getTimeDiff("20:00:00-07"));
Here is solution use utc() from moment()
const v="06:00:00+00"
const fmt = "hh:mm:ss Z"
const m = moment(v, fmt).diff(moment().utc(v, fmt).startOf('day'));
console.log(m/(3600*1000)); -> 6
With time zone
// Here is time zone +01.00
const v="06:00:00+01.00"
console.log(m/(3600*1000)); -> 5
// Here is time zone -01.00
const v="06:00:00-01.00"
console.log(m/(3600*1000)); -> 7
for country-based like UTC+08:45 you need to take care of denominator.
I have a unix timestamp: 1368435600. And a duration in minutes: 75 for example.
Using javascript I need to:
Convert the timestamp to a string format hours:mins (09:00)
Add n minutes to the timestamp: timestamp + 75mins
I tried the moment.js library:
end_time = moment(start_time).add('m', booking_service_duration);
booking_service_duration was 75 but it added an hour. I'd also rather not have to use another js library
To add 75 minutes, just multiply by 60 to get the number of seconds, and add that to the timestamp:
timestamp += 75 * 60
To convert to hours:mins you will have to do a bit more math:
var hours = Math.floor(timestamp/60/60),
mins = Math.floor((timestamp - hours * 60 * 60) / 60),
output = hours%24+":"+mins;
Unix time is the number of seconds that have elapsed since 1 January 1970 UTC.
To move that time forward you simply add the number of seconds.
So once you have the minutes, the new timestamp is oldTime + 60*minutes
For the conversion look up parsing libraries, there is code out there for this, do some research.
So you want to convert a timestamp you have, timestamp, to locale time string after adding some time interval, specifically minutes, to it.
Whether you have a kind of date-time string or a kind of epoch mili/seconds, just create a Date object:
const date = new Date(timestamp);
Keep in mind since what you need to do require to add/substract some numbers (your case: minutes) to another number, not some date object or some date-time string, and that number is the epoch mili/secods of your date. So, always you will need the number representation of your date in mili/seconds. JavaScript Date.prototype.getTime() does return epoch miliseconds of your date. Use it:
const miliseconds = date.getTime();
Add as many as miliseconds to it:
const newMiliseconds = miliseconds + (75 * 60 * 1000);
After that, as you said you need a date-time string, well a portion of it; locale time string, you will need to go all the way back; from numbers to date object and to a date-time string:
const newDate = new Date(newMiliseconds);
const newTimestamp = newDate.toString();
Or instead of getting the whole string of it, use the following specialized method to get the format/portion of the string representation of the date object that you like directly:
const newTimestamp = newDate.toLocaleTimeString(); // "12:41:43"
Finally, all you have to do is to just strip the last semicolon and seconds to get hours:minutes format:
const newHoursMins = newTimestamp.slice(0, -3);
Better make a function of it:
function timestampPlus(timestamp, milisecondsDifference, toStringFunc = Date.prototype.toString) {
const date = new Date(timestamp);
const miliseconds = date.getTime();
const newMiliseconds = miliseconds + milisecondsDifference;
const newDate = new Date(newMiliseconds);
const newTimestamp = toStringFunc.call(newDate); // a bit advanced stuff here to let you define once and use whatever kind to string method you want to use, defaults to toString()
return newTimestamp;
}
I left the final formatting out here. You can use this for substraction as well by pasing a negative second argument. Note the seconds argument is in miliseconds and unix timestamp varies and might given to you as seconds instead, in which case you will need to convert it to miliseconds or change the above funciton definition.
function timestampPlus(timestamp, milisecondsDifference, toStringFunc = Date.prototype.toString) {
const date = new Date(timestamp);
const miliseconds = date.getTime();
const newMiliseconds = miliseconds + milisecondsDifference;
const newDate = new Date(newMiliseconds);
const newTimestamp = toStringFunc.call(newDate); // a bit advanced stuff here to let you define once and use whatever kind to string method you want to use, defaults to toString()
return newTimestamp;
}
console.log("new Date(1368435600*1000).toLocaleTimeString(): ", new Date(1368435600*1000).toLocaleTimeString())
console.log("timestampPlus(1368435600*1000, 75*60*1000, Date.prototype.toLocaleString): ", timestampPlus(1368435600*1000, 75*60*1000, Date.prototype.toLocaleTimeString))
Apart from what you need, for last parameter, toStringFunc, your options vary and encompasses all related Date methods, the are on Date.prototype:
toString
toDateString
toTimeString
toLocaleString
toLocaleDateString
toLocaleTimeString
toIsoString
toUTCString
toGMTString
toJSON
I am struggling to find out the beginning of day factoring in timezones in javascript. Consider the following:
var raw_time = new Date(this.created_at);
var offset_time = new Date(raw_hour.getTime() + time_zone_offset_in_ms);
// This resets timezone to server timezone
var offset_day = new Date(offset_time.setHours(0,0,0,0))
// always returns 2011-12-08 05:00:00 UTC, no matter what the offset was!
// This has the same issue:
var another_approach_offset_day = new Date(offset_time.getFullYear(),offset_time.getMonth(),offset_time.getHours())
I expect when i pass a Pacific Timezone offset, to get: 2011-12-08 08:00:00 UTC and so on.
What is the correct way to achieve this?
I think that part of the issue is that setHours method sets the hour (from 0 to 23), according to local time.
Also note that I am using javascript embedded in mongo, so I am unable to use any additional libraries.
Thanks!
Jeez, so this was really hard for me, but here is the final solution that I came up with the following solution. The trick was I need to use setHours or SetUTCHours to get the beginning of a day -- the only choices I have are system time and UTC. So I get the beginning of a UTC day, then add back the offset!
// Goal is given a time and a timezone, find the beginning of day
function(timestamp,selected_timezone_offset) {
var raw_time = new Date(timestamp)
var offset_time = new Date(raw_time.getTime() + selected_timezone_offset);
offset_time.setUTCHours(0,0,0,0);
var beginning_of_day = new Date(offset_time.getTime() - selected_timezone_offset);
return beginning_of_day;
}
In JavaScript all dates are stored as UTC. That is, the serial number returned by date.valueOf() is the number of milliseconds since 1970-01-01 00:00:00 UTC. But, when you examine a date via .toString() or .getHours(), etc., you get the value in local time. That is, the local time of the system running the script. You can get the value in UTC with methods like .toUTCString() or .getUTCHours(), etc.
So, you can't get a date in an arbitrary timezone, it's all UTC (or local). But, of course, you can get a string representation of a date in whatever timezone you like if you know the UTC offset. The easiest way would be to subtract the UTC offset from the date and call .getUTCHours() or .toUTCString() or whatever you need:
var d = new Date();
d.setMinutes(d.getMinutes() - 480); // get pacific standard time
d.toUTCString(); // returns "Fri, 9 Dec 2011 12:56:53 UTC"
Of course, you'll need to ignore that "UTC" at the end if you use .toUTCString(). You could just go:
d.toUTCString().replace(/UTC$/, "PST");
Edit: Don't worry about when timezones overlap date boundaries. If you pass setHours() a negative number, it will subtract those hours from midnight yesterday. Eg:
var d = new Date(2011, 11, 10, 15); // d represents Dec 10, 2011 at 3pm local time
d.setHours(-1); // d represents Dec 9, 2011 at 11pm local time
d.setHours(-24); // d represents Dec 8, 2011 at 12am local time
d.setHours(52); // d represents Dec 10, 2011 at 4am local time
Where does the time_zone_offset_in_ms variable you use come from? Perhaps it is unreliable, and you should be using Date's getTimezoneOffset() method. There is an example at the following URL:
http://www.w3schools.com/jsref/jsref_getTimezoneOffset.asp
If you know the date from a different date string you can do the following:
var currentDate = new Date(this.$picker.data('date'));
var today = new Date();
today.setHours(0, -currentDate.getTimezoneOffset(), 0, 0);
(based on the codebase for a project I did)
var aDate = new Date();
var startOfTheDay = new Date(aDate.getTime() - aDate.getTime() % 86400000)
Will create the beginning of the day, of the day in question
You can make use of Intl.DateTimeFormat. This is also how luxon handles timezones.
The code below can convert any date with any timezone to its beginging/end of the time.
const beginingOfDay = (options = {}) => {
const { date = new Date(), timeZone } = options;
const parts = Intl.DateTimeFormat("en-US", {
timeZone,
hourCycle: "h23",
hour: "numeric",
minute: "numeric",
second: "numeric",
}).formatToParts(date);
const hour = parseInt(parts.find((i) => i.type === "hour").value);
const minute = parseInt(parts.find((i) => i.type === "minute").value);
const second = parseInt(parts.find((i) => i.type === "second").value);
return new Date(
1000 *
Math.floor(
(date - hour * 3600000 - minute * 60000 - second * 1000) / 1000
)
);
};
const endOfDay = (...args) =>
new Date(beginingOfDay(...args).getTime() + 86399999);
const beginingOfYear = () => {};
console.log(beginingOfDay({ timeZone: "GMT" }));
console.log(endOfDay({ timeZone: "GMT" }));
console.log(beginingOfDay({ timeZone: "Asia/Tokyo" }));
console.log(endOfDay({ timeZone: "Asia/Tokyo" }));