How to convert Moment.js date to users local timezone? - javascript

I use the Moment.js and Moment-Timezone frameworks, and have a Moment.js date object which is explicitly in UTC timezone. How can I convert that to the current timezone of the browser?
var testDateUtc = moment.tz("2015-01-30 10:00:00", "UTC");
var localDate = ???
So it would be fine if I could find out the users local time zone; or alternatively I'd like to convert the date object into another data object which just uses the "local timezone", no matter what that actually is.

You do not need to use moment-timezone for this. The main moment.js library has full functionality for working with UTC and the local time zone.
var testDateUtc = moment.utc("2015-01-30 10:00:00");
var localDate = moment(testDateUtc).local();
From there you can use any of the functions you might expect:
var s = localDate.format("YYYY-MM-DD HH:mm:ss");
var d = localDate.toDate();
// etc...
Note that by passing testDateUtc, which is a moment object, back into the moment() constructor, it creates a clone. Otherwise, when you called .local(), it would also change the testDateUtc value, instead of just the localDate value. Moments are mutable.
Also note that if your original input contains a time zone offset such as +00:00 or Z, then you can just parse it directly with moment. You don't need to use .utc or .local. For example:
var localDate = moment("2015-01-30T10:00:00Z");

var dateFormat = 'YYYY-DD-MM HH:mm:ss';
var testDateUtc = moment.utc('2015-01-30 10:00:00');
var localDate = testDateUtc.local();
console.log(localDate.format(dateFormat)); // 2015-30-01 02:00:00
Define your date format.
Create a moment object and set the UTC flag to true on the object.
Create a localized moment object converted from the original moment
object.
Return a formatted string from the localized moment object.
See: http://momentjs.com/docs/#/manipulating/local/

Here's what I did:
var timestamp = moment.unix({{ time }});
var utcOffset = moment().utcOffset();
var local_time = timestamp.add(utcOffset, "minutes");
var dateString = local_time.fromNow();
Where {{ time }} is the utc timestamp.

Use utcOffset function.
var testDateUtc = moment.utc("2015-01-30 10:00:00");
var localDate = moment(testDateUtc).utcOffset(10 * 60); //set timezone offset in minutes
console.log(localDate.format()); //2015-01-30T20:00:00+10:00

class Time extends React.Component {
constructor(props) {
super(props)
this.state = {
parentTime: '',
localTime: '',
parentTz: ''
}
}
componentDidMount() {
const inputTz = "America/Toronto"
const originTime = "2013-11-18 11:55"
const time = moment.tz(originTime, inputTz)
const localtz = moment.tz.guess()
const date = time.clone().tz(localtz)
const formatDate = moment(date).format('MMMM Do YYYY, h:mm:ss A z')
console.log(formatDate, localtz)
this.setState({parentTime: originTime, localTime: formatDate, parentTz: inputTz })
}
render() {
const {parentTime, parentTz, localTime} = this.state
return (
<div>
<p>{parentTime}<br/> in {parentTz}<br/> to {localTime}</p>
</div>
)
}
}
ReactDOM.render(
<Time />,
document.getElementById('time')
);
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-1970-2030.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.3.0/react-dom.min.js"></script>
<div id="time"></div>
the best way to get a user's time zone is using moment-timezone
import moment from 'moment-timezone'
// using utc time here
const time = moment.tz("2021-04-14T02:08:10.370Z")
const localtz = moment.tz.guess()
const date = time.clone().tz(localtz)
const formatDate = moment(date).format('MMMM Do YYYY, h:mm:ss A z')
console.log(formatDate)
this way you will be able to convert your time into a local timezone specific time

Related

Check if an iso string date is same or before an hour using moment

I've a string date in ISO format and a string in format HH:mm.
I want to know if the hour of the string ISO date is same or before the string in format HH:mm.
Example:
const isoDateString = '2021-09-28T07:30:00Z' // UTC
const hour = '07:30' // not UTC
-> result true
---
const isoDateString = '2021-09-28T07:30:00Z' // UTC
const hour = '08:30' // not UTC
-> result false
I'm using moment and this is my code:
const TIME_FORMAT = 'HH:mm'
const isoDateString = '2021-09-28T09:30:00Z'
const hour = '07:30'
const isHourSameOrBeforeIsoString = moment(
moment(isoDateString).format(TIME_FORMAT),
).isSameOrBefore(moment(hour, TIME_FORMAT));
console.log(isHourSameOrBeforeIsoString)
It doesn't work. It returns false in both cases. Why?
Use moment.utc() when constructing your iso date string because you should handle that as in UTC.
I also added TIME_FORMAT inside moment constructor of formatted iso date string.
const TIME_FORMAT = 'HH:mm'
const isoDateString = '2021-09-28T09:30:00Z'
const hour = '07:30'
const isHourSameOrBeforeIsoString = moment(
moment.utc(isoDateString).format(TIME_FORMAT), TIME_FORMAT
).isSameOrBefore(moment(hour, TIME_FORMAT));
console.log(isHourSameOrBeforeIsoString)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Here is a more reasonable way to check in my opinion:
The logic you had was correct, but the reason it is returning false is because your isoDateString is returning 8:30 and the hour you are comparing it to is 7:30, like Krzysztof mentioned in their comment, it could be a time zone issue:
var format = 'hh:mm'
// var time = moment() gives you current time. no format required.
var time = moment('2021-09-28T09:30:00Z',format),
testTime = moment('07:30', format);
console.log(moment(time).format(format));
console.log(moment(testTime).format(format));
if (time.isSameOrBefore(testTime)) {
console.log('is before')
}
if(time.isSameOrAfter(testTime)){
console.log('is after')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" referrerpolicy="no-referrer"></script>

How to convert a date in specific timezone to utc

I am having a date string '2021-09-27 07:43' I also have the info that the date is in (GMT-8:00) Alaska time zone. I am in a different local timezone. When i convert this date to UTC , it is taking my timezone as the reference timezone.
const str = new Date().toLocaleString('en-US', { timeZone: 'Etc/GMT' });
How to do it with respect to a specific time zone as the reference rather than my local time?
You can convert it using moment.js.
see Example:
var input = '2021-09-27 07:43';
var fmt = 'YYYY-MM-DD HH:mm'; // must match the input
var zone = 'Etc/GMT';
var m = moment.tz(input, fmt, zone);
m.utc();
var s = m.format(fmt) // result:
console.log(s);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.11/moment-timezone-with-data-2010-2020.min.js"></script>
Try:
let myDate = "2021-09-27 07:43";
let myDateUTC = new Date(myDate + " UTC-8"); // 2021-09-27T15:43:00.000Z

How can I get the ISO format for date and time in javascript?

I have two separate fields of date and time:-
const date = 2020-12-10;
const time = 22:00;
expected output:-
2020-12-10T10:00:00Z
I'm following this approach but the time in coming wrong:-
const date = DateUtil.getFullDateString(this.state.date_value);
const time = moment(this.state.time_value, ['HH.mm']).format('hh:mm a');
const momentObj = moment(date + time, 'YYYY-MM-DD HH:mm');
const dateTime = momentObj.toISOString();
the output of time is coming 18:30:00 but need to have 10:00:00
2020-12-10T18:30:00Z
You could parse date and time one by one, then add time to date and finally format as you want.
const date = '2020-12-10';
const time = '22:00';
const momentDate = moment(date).utc().startOf('day'); // utc() to avoid the offset
console.log(momentDate);
const momentTime = moment(time, 'HHmm').format('HH:mm');
console.log(momentTime);
const resultTime = momentDate.add(momentTime);
console.log(resultTime);
// Format as you want
console.log(resultTime.format('LLL'));
console.log(resultTime.format('YYYY-MM-DDThh:mm:ss.SSSA[Z]'));
console.log(resultTime.toISOString());
<script src="https://momentjs.com/downloads/moment.js"></script>
See this in order to know how to manage the UTC offset.

Convert time of a known timezone to local timezone in moment js

I'm trying to convert the time ( time alone ) from a known timezone to my local timezone with Moment.js.
I wrote the following function and, I am getting invalidDate as the output.
const convertToLocalTime = (time, tz) => {
const t = moment.tz(time, tz)
const localTime = t.local()
}
time is just time; without any date eg: 10:06 am and,
tz is a timezone string for eg: Europe/Berlin
What am I doing wrong?
See Parsing in Zone:
The moment.tz constructor takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier.
Since your input (10:06 am) is not in ISO 8601/RFC 2822 recognized format (see moment(String) docs), you have to pass format parameter as shown in moment(String, String).
Here a live sample:
const convertToLocalTime = (time, tz) => {
const t = moment.tz(time, 'hh:mm a', tz)
const localTime = t.local()
return localTime;
}
const res = convertToLocalTime("10:06 am", 'Europe/Berlin');
console.log( res.format('hh:mm a') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data-2012-2022.min.js"></script>

Moment Js UTC to Local Time

I'm trying to convert UTC time to the local time. I've been following this example from this link: http://jsfiddle.net/FLhpq/4/light/. I can't seem to get the right local output. For example, if its 10: 30 am in here, instead of getting 10:30 ill get 15: 30. Here is my code:
var date = moment.utc().format('YYYY-MM-DD HH:mm:ss');
var localTime = moment.utc(date).toDate();
localTime = moment(localTime).format('YYYY-MM-DD HH:mm:ss');
console.log("moment: " + localTime);
No matter what I do the time always comes out at UTC time. I live in Houston so I know timezone is the issue. I've followed the code in the link but can seem to get the local time. What am I doing wrong?
To convert UTC time to Local you have to use moment.local().
For more info see docs
Example:
var date = moment.utc().format('YYYY-MM-DD HH:mm:ss');
console.log(date); // 2015-09-13 03:39:27
var stillUtc = moment.utc(date).toDate();
var local = moment(stillUtc).local().format('YYYY-MM-DD HH:mm:ss');
console.log(local); // 2015-09-13 09:39:27
Demo:
var date = moment.utc().format();
console.log(date, "- now in UTC");
var local = moment.utc(date).local().format();
console.log(local, "- UTC now to local");
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
Try this:
let utcTime = "2017-02-02 08:00:13";
var local_date= moment.utc(utcTime).local().format('YYYY-MM-DD HH:mm:ss');
let utcTime = "2017-02-02 08:00:13.567";
var offset = moment().utcOffset();
var localText = moment.utc(utcTime).utcOffset(offset).format("L LT");
Try this JsFiddle
To convert UTC to local time
let UTC = moment.utc()
let local = moment(UTC).local()
Or you want directly get the local time
let local = moment()
var UTC = moment.utc()
console.log(UTC.format()); // UTC time
var cLocal = UTC.local()
console.log(cLocal.format()); // Convert UTC time
var local = moment();
console.log(local.format()); // Local time
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
Note: please update the date format accordingly.
Format Date
__formatDate: function(myDate){
var ts = moment.utc(myDate);
return ts.local().format('D-MMM-Y');
}
Format Time
__formatTime: function(myDate){
var ts = moment.utc(myDate);
return ts.local().format('HH:mm');
},
This is old question I see, but I didn't really get what I was looking for. I had a UTC datetime which was formatted without timezone. So I had to do this:
let utcDatetime = '2021-05-31 10:20:00';
let localDatetime = moment(utcDatetime + '+00:00').local().format('YYYY-MM-DD HH:mm:ss');
I've written this Codesandbox for a roundtrip from UTC to local time and from local time to UTC. You can change the timezone and the format. Enjoy!
Full Example on Codesandbox (DEMO):
https://codesandbox.io/s/momentjs-utc-to-local-roundtrip-foj57?file=/src/App.js
This is what worked for me, it required moment-tz as well as moment though.
const guess = moment.utc(date).tz(moment.tz.guess());
const correctTimezone = guess.format()
Here is what I do using Intl api:
let currentTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone; // For example: Australia/Sydney
this will return a time zone name. Pass this parameter to the following function to get the time
let dateTime = new Date(date).toLocaleDateString('en-US',{ timeZone: currentTimeZone, hour12: true});
let time = new Date(date).toLocaleTimeString('en-US',{ timeZone: currentTimeZone, hour12: true});
you can also format the time with moment like this:
moment(new Date(`${dateTime} ${time}`)).format('YYYY-MM-DD[T]HH:mm:ss');
I've created one function which converts all the timezones into local time.
Requirements:
1. npm i moment-timezone
function utcToLocal(utcdateTime, tz) {
var zone = moment.tz(tz).format("Z") // Actual zone value e:g +5:30
var zoneValue = zone.replace(/[^0-9: ]/g, "") // Zone value without + - chars
var operator = zone && zone.split("") && zone.split("")[0] === "-" ? "-" : "+" // operator for addition subtraction
var localDateTime
var hours = zoneValue.split(":")[0]
var minutes = zoneValue.split(":")[1]
if (operator === "-") {
localDateTime = moment(utcdateTime).subtract(hours, "hours").subtract(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
} else if (operator) {
localDateTime = moment(utcdateTime).add(hours, "hours").add(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
} else {
localDateTime = "Invalid Timezone Operator"
}
return localDateTime
}
utcToLocal("2019-11-14 07:15:37", "Asia/Kolkata")
//Returns "2019-11-14 12:45:37"

Categories