momentJS - Convert UTC timestamp to local time (REACT JS) - javascript

I have a UTC timestamp coming down from the server side. It's a static timestamp (for example: 11:30)
I want to convert 11:30 to users local timezone.
I did this:
const SessionStartTime = () => {
const startTime = moment.sessionStartTime
const convertTime = moment.utc(startTime).toDate()
const localTime = moment(convertTime)
console.log(localTime)
return <span>{new Date(startTime)}</span>
}
which converts the time to clients REAL-TIME which is not what I'm looking for.
Any tips?
edit:
After reading the docs I came up with this
const SessionStartTime = () => {
const dateFormat = "HH:mm"
const startTime = sessionStartTime
const localTime = startTime.local()
return <span>{localTime.format(dateFormat)}</span>
}
but it doesn't do anything.

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 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.

Moment Timezone not returning expected result

I might be doing something silly here. But essentially, the time in Lisbon right now is 12:27 PM
but the following returns 14:27 (EU central time)
const time = moment.tz("Europe/Lisbon")
const timeZone = "Europe/Lisbon"
const format = "'HH[:]mm'"
const startMoment = moment.tz(item.startTime, format, timeZone);
const endMoment = moment(item.endTime, format, timeZone);
return time.isBetween(startMoment, endMoment);
I tried several combinations and I get the wrong answer everytime. For example if I set timeZone to be "Europe/Warsaw" it returns 15:27 whereas it should be 13:27.
EDIT: const currentTime = moment().tz("Europe/London").format() returns the correct time for London. However, the return statement moment(currentTime).isBetween(startMoment, endMoment) still reads "moment(correntTime)" as the local time.
isBetween return boolean . And isBetween runs on date object. You are trying to run on time zone object. which is different from date object
const time = moment.tz("Europe/Lisbon")
const timeZone = "Europe/Lisbon"
const format = "'HH[:]mm'"
const startMoment = moment().subtract(8, 'months').tz(timeZone).format();
const endMoment = moment(new Date()).tz(timeZone).format() ;
console.log("startMoment",startMoment)
console.log("endMoment",endMoment)
console.log(moment.tz(new Date(),"Europe/Lisbon").format())
console.log(moment('2020-09-30').isBetween(startMoment, endMoment));
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.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"

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

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

Categories