Okay, say JSON parse string UTC date as below:
2012-11-29 17:00:34 UTC
Now if I want to convert this UTC date to my local time, how can I do this?
How do I format it to something else like yyyy-MM-dd HH:mm:ss z?
This date.toString('yyyy-MM-dd HH:mm:ss z'); never work out :/
Try:
var date = new Date('2012-11-29 17:00:34 UTC');
date.toString();
var offset = new Date().getTimezoneOffset();
offset will be the interval in minutes from Local time to UTC. To get Local time from a UTC date, you would then subtract the minutes from your date.
utc_date.setMinutes(utc_date.getMinutes() - offset);
Here is another option that outputs mm/dd/yy using toLocaleString():
const date = new Date('2012-11-29 17:00:34 UTC');
date.toLocaleString();
//output 11/29/2012
To format your date try the following function:
var d = new Date();
var fromatted = d.toLocaleFormat("%d.%m.%Y %H:%M (%a)");
But the downside of this is, that it's a non-standard function, which is not working in Chrome, but working in FF (afaik).
Chris
The solutions above are right but might crash in FireFox and Safari! and that's what webility.js is trying to solve. Check the toUTC function, it works on most of the main browers and it returns the time in ISO format
You could take a look at date-and-time api for easily date manipulation.
let now = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss', true);
console.log(now);
<script src="https://cdn.jsdelivr.net/npm/date-and-time/date-and-time.min.js"></script>
This should work
var date = new Date('2012-11-29 17:00:34 UTC');
date.toString()
This works for both Chrome and Firefox.
Not tested on other browsers.
const convertToLocalTime = (dateTime, notStanderdFormat = true) => {
if (dateTime !== null && dateTime !== undefined) {
if (notStanderdFormat) {
// works for 2021-02-21 04:01:19
// convert to 2021-02-21T04:01:19.000000Z format before convert to local time
const splited = dateTime.split(" ");
let convertedDateTime = `${splited[0]}T${splited[1]}.000000Z`;
const date = new Date(convertedDateTime);
return date.toString();
} else {
// works for 2021-02-20T17:52:45.000000Z or 1613639329186
const date = new Date(dateTime);
return date.toString();
}
} else {
return "Unknown";
}
};
// TEST
console.log(convertToLocalTime('2012-11-29 17:00:34 UTC'));
// d = "2021-09-23T15:51:48.31"
console.log(new Date(d + "z").toLocaleDateString()); // gives 9/23/2021
console.log(new Date(d + "z").toLocaleString()); // gives 9/23/2021, 10:51:48 AM
console.log(new Date(d + "z").toLocaleTimeString()); // gives 10:51:48 AM
/*
* convert server time to local time
* simbu
*/
function convertTime(serverdate) {
var date = new Date(serverdate);
// convert to utc time
var toutc = date.toUTCString();
//convert to local time
var locdat = new Date(toutc + " UTC");
return locdat;
}
Related
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
Can I convert iso date to milliseconds?
for example I want to convert this iso
2012-02-10T13:19:11+0000
to milliseconds.
Because I want to compare current date from the created date. And created date is an iso date.
Try this
var date = new Date("11/21/1987 16:00:00"); // some mock date
var milliseconds = date.getTime();
// This will return you the number of milliseconds
// elapsed from January 1, 1970
// if your date is less than that date, the value will be negative
console.log(milliseconds);
EDIT
You've provided an ISO date. It is also accepted by the constructor of the Date object
var myDate = new Date("2012-02-10T13:19:11+0000");
var result = myDate.getTime();
console.log(result);
Edit
The best I've found is to get rid of the offset manually.
var myDate = new Date("2012-02-10T13:19:11+0000");
var offset = myDate.getTimezoneOffset() * 60 * 1000;
var withOffset = myDate.getTime();
var withoutOffset = withOffset - offset;
console.log(withOffset);
console.log(withoutOffset);
Seems working. As far as problems with converting ISO string into the Date object you may refer to the links provided.
EDIT
Fixed the bug with incorrect conversion to milliseconds according to Prasad19sara's comment.
A shorthand of the previous solutions is
var myDate = +new Date("2012-02-10T13:19:11+0000");
It does an on the fly type conversion and directly outputs date in millisecond format.
Another way is also using parse method of Date util which only outputs EPOCH time in milliseconds.
var myDate = Date.parse("2012-02-10T13:19:11+0000");
Another option as of 2017 is to use Date.parse(). MDN's documentation points out, however, that it is unreliable prior to ES5.
var date = new Date(); // today's date and time in ISO format
var myDate = Date.parse(date);
See the fiddle for more details.
Yes, you can do this in a single line
let ms = Date.parse('2019-05-15 07:11:10.673Z');
console.log(ms);//1557904270673
Another possible solution is to compare current date with January 1, 1970, you can get January 1, 1970 by new Date(0);
var date = new Date();
var myDate= date - new Date(0);
Another solution could be to use Number object parser like this:
let result = Number(new Date("2012-02-10T13:19:11+0000"));
let resultWithGetTime = (new Date("2012-02-10T13:19:11+0000")).getTime();
console.log(result);
console.log(resultWithGetTime);
This converts to milliseconds just like getTime() on Date object
var date = new Date()
console.log(" Date in MS last three digit = "+ date.getMilliseconds())
console.log(" MS = "+ Date.now())
Using this we can get date in milliseconds
var date = new Date(date_string);
var milliseconds = date.getTime();
This worked for me!
if wants to convert UTC date to milliseconds
syntax : Date.UTC(year, month, ?day, ?hours, ?min, ?sec, ?milisec);
e.g :
date_in_mili = Date.UTC(2020, 07, 03, 03, 40, 40, 40);
console.log('miliseconds', date_in_mili);
In case if anyone wants to grab only the Time from a ISO Date, following will be helpful. I was searching for that and I couldn't find a question for it. So in case some one sees will be helpful.
let isoDate = '2020-09-28T15:27:15+05:30';
let result = isoDate.match(/\d\d:\d\d/);
console.log(result[0]);
The output will be the only the time from isoDate which is,
15:27
Okay, say JSON parse string UTC date as below:
2012-11-29 17:00:34 UTC
Now if I want to convert this UTC date to my local time, how can I do this?
How do I format it to something else like yyyy-MM-dd HH:mm:ss z?
This date.toString('yyyy-MM-dd HH:mm:ss z'); never work out :/
Try:
var date = new Date('2012-11-29 17:00:34 UTC');
date.toString();
var offset = new Date().getTimezoneOffset();
offset will be the interval in minutes from Local time to UTC. To get Local time from a UTC date, you would then subtract the minutes from your date.
utc_date.setMinutes(utc_date.getMinutes() - offset);
Here is another option that outputs mm/dd/yy using toLocaleString():
const date = new Date('2012-11-29 17:00:34 UTC');
date.toLocaleString();
//output 11/29/2012
To format your date try the following function:
var d = new Date();
var fromatted = d.toLocaleFormat("%d.%m.%Y %H:%M (%a)");
But the downside of this is, that it's a non-standard function, which is not working in Chrome, but working in FF (afaik).
Chris
The solutions above are right but might crash in FireFox and Safari! and that's what webility.js is trying to solve. Check the toUTC function, it works on most of the main browers and it returns the time in ISO format
You could take a look at date-and-time api for easily date manipulation.
let now = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss', true);
console.log(now);
<script src="https://cdn.jsdelivr.net/npm/date-and-time/date-and-time.min.js"></script>
This should work
var date = new Date('2012-11-29 17:00:34 UTC');
date.toString()
This works for both Chrome and Firefox.
Not tested on other browsers.
const convertToLocalTime = (dateTime, notStanderdFormat = true) => {
if (dateTime !== null && dateTime !== undefined) {
if (notStanderdFormat) {
// works for 2021-02-21 04:01:19
// convert to 2021-02-21T04:01:19.000000Z format before convert to local time
const splited = dateTime.split(" ");
let convertedDateTime = `${splited[0]}T${splited[1]}.000000Z`;
const date = new Date(convertedDateTime);
return date.toString();
} else {
// works for 2021-02-20T17:52:45.000000Z or 1613639329186
const date = new Date(dateTime);
return date.toString();
}
} else {
return "Unknown";
}
};
// TEST
console.log(convertToLocalTime('2012-11-29 17:00:34 UTC'));
// d = "2021-09-23T15:51:48.31"
console.log(new Date(d + "z").toLocaleDateString()); // gives 9/23/2021
console.log(new Date(d + "z").toLocaleString()); // gives 9/23/2021, 10:51:48 AM
console.log(new Date(d + "z").toLocaleTimeString()); // gives 10:51:48 AM
/*
* convert server time to local time
* simbu
*/
function convertTime(serverdate) {
var date = new Date(serverdate);
// convert to utc time
var toutc = date.toUTCString();
//convert to local time
var locdat = new Date(toutc + " UTC");
return locdat;
}
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"
I need to convert a date in yyyy-mm-dd like 2011-12-30 to UTC using only javascript. How?
var utc = new Date('2011-12-30').toUTCString();
jsFiddle.
If you're having problems getting the other listed solution to work in firefox or safari you can use: http://www.datejs.com/
myDate = new Date.parse("2011-12-30")
myUTCDate = Date.UTC(myDate.getFullYear(), myDate.getMonth(), myDate.getDate(), myDate.getHours(), myDate.getMinutes(), myDate.getSeconds(), myDate.getMilliseconds());
Voila!!
This is very simple method to convert String to Date in JavaScript
var msomtDate = Date.parse('Here Your Date String'+' UTC',"yyyy/MM/dd HH:mm:ss");
var toUTC = function (date) {
var newDate = new Date();
newDate.setTime(date.getTime() + (date.getTimezoneOffset() * 60 * 1000));
return newDate;
};
console.log(toUTC(new Date('2011-12-30')));