I have a web page with three dropdowns for day, month and year. If I use the JavaScript Date constructor that takes numbers, then I get a Date object for my current timezone:
new Date(xiYear, xiMonth, xiDate)
Give the correct date, but it thinks that date is GMT+01:00 due to daylight savings time.
The problem here is that I then pass this Date to an Ajax method and when the date is deserialised on the server it has been converted to GMT and so lost an hour which moves the day back by one.
Now I could just pass the day, month, and year individually into the Ajax method, but it seems that there ought to be a better way.
The accepted answer pointed me in the right direction, however just using setUTCHours() by itself changed:
Apr 5th 00:00 GMT+01:00
to
Apr 4th 23:00 GMT+01:00
I then also had to set the UTC date, month and year to end up with
Apr 5th 01:00 GMT+01:00
which is what I wanted.
using .setUTCHours() it would be possible to actually set dates in UTC-time, which would allow you to use UTC-times throughout the system.
You cannot set it using UTC in the constructor though, unless you specify a date-string.
Using new Date(Date.UTC(year, month, day, hour, minute, second)) you can create a Date-object from a specific UTC time.
Simply Set the Time Zone and Get Back According
new Date().toLocaleString("en-US", {timeZone: "America/New_York"})
Other Time-zones are as Following
var world_timezones =
[
'Europe/Andorra',
'Asia/Dubai',
'Asia/Kabul',
'Europe/Tirane',
'Asia/Yerevan',
'Antarctica/Casey',
'Antarctica/Davis',
'Antarctica/DumontDUrville',
'Antarctica/Mawson',
'Antarctica/Palmer',
'Antarctica/Rothera',
'Antarctica/Syowa',
'Antarctica/Troll',
'Antarctica/Vostok',
'America/Argentina/Buenos_Aires',
'America/Argentina/Cordoba',
'America/Argentina/Salta',
'America/Argentina/Jujuy',
'America/Argentina/Tucuman',
'America/Argentina/Catamarca',
'America/Argentina/La_Rioja',
'America/Argentina/San_Juan',
'America/Argentina/Mendoza',
'America/Argentina/San_Luis',
'America/Argentina/Rio_Gallegos',
'America/Argentina/Ushuaia',
'Pacific/Pago_Pago',
'Europe/Vienna',
'Australia/Lord_Howe',
'Antarctica/Macquarie',
'Australia/Hobart',
'Australia/Currie',
'Australia/Melbourne',
'Australia/Sydney',
'Australia/Broken_Hill',
'Australia/Brisbane',
'Australia/Lindeman',
'Australia/Adelaide',
'Australia/Darwin',
'Australia/Perth',
'Australia/Eucla',
'Asia/Baku',
'America/Barbados',
'Asia/Dhaka',
'Europe/Brussels',
'Europe/Sofia',
'Atlantic/Bermuda',
'Asia/Brunei',
'America/La_Paz',
'America/Noronha',
'America/Belem',
'America/Fortaleza',
'America/Recife',
'America/Araguaina',
'America/Maceio',
'America/Bahia',
'America/Sao_Paulo',
'America/Campo_Grande',
'America/Cuiaba',
'America/Santarem',
'America/Porto_Velho',
'America/Boa_Vista',
'America/Manaus',
'America/Eirunepe',
'America/Rio_Branco',
'America/Nassau',
'Asia/Thimphu',
'Europe/Minsk',
'America/Belize',
'America/St_Johns',
'America/Halifax',
'America/Glace_Bay',
'America/Moncton',
'America/Goose_Bay',
'America/Blanc-Sablon',
'America/Toronto',
'America/Nipigon',
'America/Thunder_Bay',
'America/Iqaluit',
'America/Pangnirtung',
'America/Atikokan',
'America/Winnipeg',
'America/Rainy_River',
'America/Resolute',
'America/Rankin_Inlet',
'America/Regina',
'America/Swift_Current',
'America/Edmonton',
'America/Cambridge_Bay',
'America/Yellowknife',
'America/Inuvik',
'America/Creston',
'America/Dawson_Creek',
'America/Fort_Nelson',
'America/Vancouver',
'America/Whitehorse',
'America/Dawson',
'Indian/Cocos',
'Europe/Zurich',
'Africa/Abidjan',
'Pacific/Rarotonga',
'America/Santiago',
'America/Punta_Arenas',
'Pacific/Easter',
'Asia/Shanghai',
'Asia/Urumqi',
'America/Bogota',
'America/Costa_Rica',
'America/Havana',
'Atlantic/Cape_Verde',
'America/Curacao',
'Indian/Christmas',
'Asia/Nicosia',
'Asia/Famagusta',
'Europe/Prague',
'Europe/Berlin',
'Europe/Copenhagen',
'America/Santo_Domingo',
'Africa/Algiers',
'America/Guayaquil',
'Pacific/Galapagos',
'Europe/Tallinn',
'Africa/Cairo',
'Africa/El_Aaiun',
'Europe/Madrid',
'Africa/Ceuta',
'Atlantic/Canary',
'Europe/Helsinki',
'Pacific/Fiji',
'Atlantic/Stanley',
'Pacific/Chuuk',
'Pacific/Pohnpei',
'Pacific/Kosrae',
'Atlantic/Faroe',
'Europe/Paris',
'Europe/London',
'Asia/Tbilisi',
'America/Cayenne',
'Africa/Accra',
'Europe/Gibraltar',
'America/Godthab',
'America/Danmarkshavn',
'America/Scoresbysund',
'America/Thule',
'Europe/Athens',
'Atlantic/South_Georgia',
'America/Guatemala',
'Pacific/Guam',
'Africa/Bissau',
'America/Guyana',
'Asia/Hong_Kong',
'America/Tegucigalpa',
'America/Port-au-Prince',
'Europe/Budapest',
'Asia/Jakarta',
'Asia/Pontianak',
'Asia/Makassar',
'Asia/Jayapura',
'Europe/Dublin',
'Asia/Jerusalem',
'Asia/Kolkata',
'Indian/Chagos',
'Asia/Baghdad',
'Asia/Tehran',
'Atlantic/Reykjavik',
'Europe/Rome',
'America/Jamaica',
'Asia/Amman',
'Asia/Tokyo',
'Africa/Nairobi',
'Asia/Bishkek',
'Pacific/Tarawa',
'Pacific/Enderbury',
'Pacific/Kiritimati',
'Asia/Pyongyang',
'Asia/Seoul',
'Asia/Almaty',
'Asia/Qyzylorda',
'Asia/Qostanay',
'Asia/Aqtobe',
'Asia/Aqtau',
'Asia/Atyrau',
'Asia/Oral',
'Asia/Beirut',
'Asia/Colombo',
'Africa/Monrovia',
'Europe/Vilnius',
'Europe/Luxembourg',
'Europe/Riga',
'Africa/Tripoli',
'Africa/Casablanca',
'Europe/Monaco',
'Europe/Chisinau',
'Pacific/Majuro',
'Pacific/Kwajalein',
'Asia/Yangon',
'Asia/Ulaanbaatar',
'Asia/Hovd',
'Asia/Choibalsan',
'Asia/Macau',
'America/Martinique',
'Europe/Malta',
'Indian/Mauritius',
'Indian/Maldives',
'America/Mexico_City',
'America/Cancun',
'America/Merida',
'America/Monterrey',
'America/Matamoros',
'America/Mazatlan',
'America/Chihuahua',
'America/Ojinaga',
'America/Hermosillo',
'America/Tijuana',
'America/Bahia_Banderas',
'Asia/Kuala_Lumpur',
'Asia/Kuching',
'Africa/Maputo',
'Africa/Windhoek',
'Pacific/Noumea',
'Pacific/Norfolk',
'Africa/Lagos',
'America/Managua',
'Europe/Amsterdam',
'Europe/Oslo',
'Asia/Kathmandu',
'Pacific/Nauru',
'Pacific/Niue',
'Pacific/Auckland',
'Pacific/Chatham',
'America/Panama',
'America/Lima',
'Pacific/Tahiti',
'Pacific/Marquesas',
'Pacific/Gambier',
'Pacific/Port_Moresby',
'Pacific/Bougainville',
'Asia/Manila',
'Asia/Karachi',
'Europe/Warsaw',
'America/Miquelon',
'Pacific/Pitcairn',
'America/Puerto_Rico',
'Asia/Gaza',
'Asia/Hebron',
'Europe/Lisbon',
'Atlantic/Madeira',
'Atlantic/Azores',
'Pacific/Palau',
'America/Asuncion',
'Asia/Qatar',
'Indian/Reunion',
'Europe/Bucharest',
'Europe/Belgrade',
'Europe/Kaliningrad',
'Europe/Moscow',
'Europe/Simferopol',
'Europe/Kirov',
'Europe/Astrakhan',
'Europe/Volgograd',
'Europe/Saratov',
'Europe/Ulyanovsk',
'Europe/Samara',
'Asia/Yekaterinburg',
'Asia/Omsk',
'Asia/Novosibirsk',
'Asia/Barnaul',
'Asia/Tomsk',
'Asia/Novokuznetsk',
'Asia/Krasnoyarsk',
'Asia/Irkutsk',
'Asia/Chita',
'Asia/Yakutsk',
'Asia/Khandyga',
'Asia/Vladivostok',
'Asia/Ust-Nera',
'Asia/Magadan',
'Asia/Sakhalin',
'Asia/Srednekolymsk',
'Asia/Kamchatka',
'Asia/Anadyr',
'Asia/Riyadh',
'Pacific/Guadalcanal',
'Indian/Mahe',
'Africa/Khartoum',
'Europe/Stockholm',
'Asia/Singapore',
'America/Paramaribo',
'Africa/Juba',
'Africa/Sao_Tome',
'America/El_Salvador',
'Asia/Damascus',
'America/Grand_Turk',
'Africa/Ndjamena',
'Indian/Kerguelen',
'Asia/Bangkok',
'Asia/Dushanbe',
'Pacific/Fakaofo',
'Asia/Dili',
'Asia/Ashgabat',
'Africa/Tunis',
'Pacific/Tongatapu',
'Europe/Istanbul',
'America/Port_of_Spain',
'Pacific/Funafuti',
'Asia/Taipei',
'Europe/Kiev',
'Europe/Uzhgorod',
'Europe/Zaporozhye',
'Pacific/Wake',
'America/New_York',
'America/Detroit',
'America/Kentucky/Louisville',
'America/Kentucky/Monticello',
'America/Indiana/Indianapolis',
'America/Indiana/Vincennes',
'America/Indiana/Winamac',
'America/Indiana/Marengo',
'America/Indiana/Petersburg',
'America/Indiana/Vevay',
'America/Chicago',
'America/Indiana/Tell_City',
'America/Indiana/Knox',
'America/Menominee',
'America/North_Dakota/Center',
'America/North_Dakota/New_Salem',
'America/North_Dakota/Beulah',
'America/Denver',
'America/Boise',
'America/Phoenix',
'America/Los_Angeles',
'America/Anchorage',
'America/Juneau',
'America/Sitka',
'America/Metlakatla',
'America/Yakutat',
'America/Nome',
'America/Adak',
'Pacific/Honolulu',
'America/Montevideo',
'Asia/Samarkand',
'Asia/Tashkent',
'America/Caracas',
'Asia/Ho_Chi_Minh',
'Pacific/Efate',
'Pacific/Wallis',
'Pacific/Apia',
'Africa/Johannesburg'
];
var d = new Date(xiYear, xiMonth, xiDate);
d.setTime( d.getTime() + d.getTimezoneOffset()*60*1000 );
This answer is tailored specifically to the original question, and will not give the answer you necessarily expect. In particular, some people will want to subtract the timezone offset instead of add it. Remember though that the whole point of this solution is to hack javascript's date object for a particular deserialization, not to be correct in all cases.
I believe you need the createDateAsUTC function (please compare with convertDateToUTC)
function createDateAsUTC(date) {
return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
}
function convertDateToUTC(date) {
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}
I don't believe this is possible - there is no ability to set the timezone on a Date object after it is created.
And in a way this makes sense - conceptually (if perhaps not in implementation); per http://en.wikipedia.org/wiki/Unix_timestamp (emphasis mine):
Unix time, or POSIX time, is a system for describing instants in time, defined as the number of seconds elapsed since midnight Coordinated Universal Time (UTC) of Thursday, January 1, 1970.
Once you've constructed one it will represent a certain point in "real" time. The time zone is only relevant when you want to convert that abstract time point into a human-readable string.
Thus it makes sense you would only be able to change the actual time the Date represents in the constructor. Sadly it seems that there is no way to pass in an explicit timezone - and the constructor you are calling (arguably correctly) translates your "local" time variables into GMT when it stores them canonically - so there is no way to use the int, int, int constructor for GMT times.
On the plus side, it's trivial to just use the constructor that takes a String instead. You don't even have to convert the numeric month into a String (on Firefox at least), so I was hoping a naive implementation would work. However, after trying it out it works successfully in Firefox, Chrome, and Opera but fails in Konqueror ("Invalid Date") , Safari ("Invalid Date") and IE ("NaN"). I suppose you'd just have a lookup array to convert the month to a string, like so:
var months = [ '', 'January', 'February', ..., 'December'];
function createGMTDate(xiYear, xiMonth, xiDate) {
return new Date(months[xiMonth] + ' ' + xiDate + ', ' + xiYear + ' 00:00:00 GMT');
}
I know this is old but if it helps you could use moment and moment time zone. If you haven't seen them take a look.
http://momentjs.com/timezone/
http://momentjs.com/
two really handy time manipulation libraries.
If you want to deal with the slightly different, but related, problem of creating a Javascript Date object from year, month, day, ..., including timezone – that is, if you want to parse a string into a Date – then you apparently have to do an infuriatingly complicated dance:
// parseISO8601String : string -> Date
// Parse an ISO-8601 date, including possible timezone,
// into a Javascript Date object.
//
// Test strings: parseISO8601String(x).toISOString()
// "2013-01-31T12:34" -> "2013-01-31T12:34:00.000Z"
// "2013-01-31T12:34:56" -> "2013-01-31T12:34:56.000Z"
// "2013-01-31T12:34:56.78" -> "2013-01-31T12:34:56.780Z"
// "2013-01-31T12:34:56.78+0100" -> "2013-01-31T11:34:56.780Z"
// "2013-01-31T12:34:56.78+0530" -> "2013-01-31T07:04:56.780Z"
// "2013-01-31T12:34:56.78-0330" -> "2013-01-31T16:04:56.780Z"
// "2013-01-31T12:34:56-0330" -> "2013-01-31T16:04:56.000Z"
// "2013-01-31T12:34:56Z" -> "2013-01-31T12:34:56.000Z"
function parseISO8601String(dateString) {
var timebits = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2})(?::([0-9]*)(\.[0-9]*)?)?(?:([+-])([0-9]{2})([0-9]{2}))?/;
var m = timebits.exec(dateString);
var resultDate;
if (m) {
var utcdate = Date.UTC(parseInt(m[1]),
parseInt(m[2])-1, // months are zero-offset (!)
parseInt(m[3]),
parseInt(m[4]), parseInt(m[5]), // hh:mm
(m[6] && parseInt(m[6]) || 0), // optional seconds
(m[7] && parseFloat(m[7])*1000) || 0); // optional fraction
// utcdate is milliseconds since the epoch
if (m[9] && m[10]) {
var offsetMinutes = parseInt(m[9]) * 60 + parseInt(m[10]);
utcdate += (m[8] === '+' ? -1 : +1) * offsetMinutes * 60000;
}
resultDate = new Date(utcdate);
} else {
resultDate = null;
}
return resultDate;
}
That is, you create a 'UTC time' using the date without timezone (so you know what locale it's in, namely the UTC 'locale', and it's not defaulted to the local one), and then manually apply the indicated timezone offset.
Wouldn't it have been nice if someone had actually thought about the Javascript date object for more than, oooh, five minutes....
d = new Date();
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
nd = new Date(utc + (3600000*offset));
offset value base on which location time zone you would like to set
For India offset value +5.5,
New York offset value -4,
London offset value +1
for all location offset Wiki List of UTC time offsets
// My clock 2018-07-25, 00:26:00 (GMT+7)
let date = new Date(); // 2018-07-24:17:26:00 (Look like GMT+0)
const myTimeZone = 7; // my timeZone
// my timeZone = 7h = 7 * 60 * 60 * 1000 (millisecond);
// 2018-07-24:17:26:00 = x (milliseconds)
// finally, time in milliseconds (GMT+7) = x + myTimezone
date.setTime( date.getTime() + myTimeZone * 60 * 60 * 1000 );
// date.toISOString() = 2018-07-25, 00:26:00 (GMT+7)
getTimeZoneOffset is minus for UTC + z.
var d = new Date(xiYear, xiMonth, xiDate);
if(d.getTimezoneOffset() > 0){
d.setTime( d.getTime() + d.getTimezoneOffset()*60*1000 );
}
This may help someone, put UTC at the end of what you pass in to the new constructor
At least in chrome you can say var date = new Date("2014-01-01 11:00:00 UTC")
One line solution
new Date(new Date(1422524805305).getTime() - 330*60*1000)
Instead of 1422524805305, use the timestamp in milliseconds
Instead of 330, use your timezone offset in minutes wrt. GMT (eg India +5:30 is 5*60+30 = 330 minutes)
The easiest way that I have found to get the correct date is using datejs.
http://www.datejs.com/
I get my dates via Ajax in this format as a string: '2016-01-12T00:00:00'
var yourDateString = '2016-01-12T00:00:00';
var yourDate = new Date(yourDateString);
console.log(yourDate);
if (yourDate.getTimezoneOffset() > 0){
yourDate = new Date(yourDateString).addMinutes(yourDate.getTimezoneOffset());
}
console.log(yourDate);
Console will read:
Mon Jan 11 2016 19:00:00 GMT-0500 (Eastern Standard Time)
Tue Jan 12 2016 00:00:00 GMT-0500 (Eastern Standard Time)
https://jsfiddle.net/vp1ena7b/3/
The 'addMinutes' comes from datejs, you could probably do this in pure js on your own, but I already had datejs in my project so I found a way to use it to get the correct dates.
I thought that this might help someone...
This code will return your Date object formatted with the browser timezone.
Date.prototype.timezone = function () {
this.setHours(this.getHours() + (new Date().getTimezoneOffset() / 60));
return this;
}
Edit:
To avoid to pollute the Date API, the above function can be transformed into a utility function. The function takes a Date object, and returns a mutated Date object.
function setTimeZone(date) {
date.setHours(date.getHours() + (new Date().getTimezoneOffset() / 60));
return date;
}
Here is a function that you can use to achieve a date object:
const getUTCDate = (date) => {
const d = new Date(date);
const utcDate = new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
return utcDate;
}
const string = '1930-08-12T00:00:00.000000Z';
const utcDate = getUTCDate(string);
// returns Tue Aug 12 1930 00:00:00 GMT-0800 (Pacific Daylight Time)
any mileage in
var d = new Date(xiYear, xiMonth, xiDate).toLocaleString();
const date = new Date("2020-12-16 17:45:00 UTC");
Works fine.
I was having a similar problem with a date picker. My research led to a very simple solution, without any extra libraries or hardcoded multipliers.
Key info:
ISO is the Javascript preferred date standard. Assume date utilities will likely return date values in that format.
My date picker displays the date in a localized format: mm/dd/yyyy
However, it returns the date value in the ISO format: yyyy-mm-dd
//Select "08/12/2020" in Date Picker date_input
var input = $('#date_input').val(); //input: 2020-08-12
Date.getTimezoneOffset() returns the offset in minutes.
Examples:
If you use the default returned date value without modifying the string format, the Date might not get set to your timezone. This can lead to unexpected results.
var input = $('#date_input').val(); //input: 2020-08-12
var date = new Date(input); //This get interpreted as an ISO date, already in UTC
//date: Tue Aug 11 2020 20:00:00 GMT-0400 (Eastern Daylight Time)
//date.toUTCString(): Wed, 12 Aug 2020 00:00:00 GMT
//date.toLocaleDateString('en-US'): 8/11/2020
Using a different date string format than the ISO standard yyyy-mm-dd applies your timezone to the Date.
var date = new Date("08/12/2020"); //This gets interpreted as local timezone
//date: Wed Aug 12 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
//date.toUTCString(): Wed, 12 Aug 2020 04:00:00 GMT
//date.toLocaleDateString('en-US'): 8/12/2020
Solution:
To apply your timezone to the format-agnostic Date without doing string manipulation, use Date.getTimezoneOffset() with Minutes. This works with either original date string format (i.e. UTC dates or localized dates). It provides a consistent result which can then be converted accurately to UTC for storage or interacting with other code.
var input = $('#date_input').val();
var date = new Date(input);
date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
//date: Wed Aug 12 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
//date.toUTCString(): Wed, 12 Aug 2020 04:00:00 GMT
//date.toLocaleDateString('en-US'): 8/12/2020
It's actually not very hard at all to do this, but it certainly isn't intuitive to come up with the solution. There are some really convoluted answers here (though also some nice ones). Here's what I came up with to make sure my server timestamps would match my local timestamps, no matter what timezone my deployed server happened to be in.
(CET = Central European Timezone, which just happens to be my personal timezone; you can get the offset of any given timezone and calculate it and even make it an argument if you like, but for my purpose, I just needed to get my dates to all be the single desired consistent timezone.)
const convertDateToCET = function(date) {
date = new Date(date)
// let startTime = date.getTime();
const cetOffset = -120; // this is the number you get from running
// `(new Date()).getTimezoneOffset()` if you're on a machine in CET
const offsetFromCET = (date.getTimezoneOffset() - cetOffset);
const cetMillsecondOffset = ( cetOffset* 60 * 1000);
date = new Date( date.getTime() - cetMillsecondOffset )
// let endTime = date.getTime()
// console.log("updated date from",startTime,"to",endTime)
return date;
},
Using this, you just make a time the way you would expect, e.g.
let myDate = new Date("12-4-2021")
myDate.setHour(14)
myDate.setMinute(30)
// now myDate is 2:30pm, December 4th, 2021, in whatever the timezone the machine of code running happens to be in
myDate = convertDateToCET(myDate)
// now myDate will show up as 2:30pm, Dec 4th, 2021, mapped into your local timezone
// so, if you're in the UK, and one hour behind CET, myDate is now 1:30pm, Dec 4th, 2021
The key here is date.getTimezoneOffset(). If you're actually in CET, that number will be -120, and so it cancels out, making no difference (so CET results in CET out). If you're in the UK, one hour behind CET, that output would be -60, which means -60 + 120 = +60 which results in us changing the input time by one hour, and so on.
It probably makes more sense to convert everything and use everything in UTC for a case like this, but given that all of my input time is in CET and I'd originally developed the system based on how things looked locally on my machine, this utility allowed me to convert the existing code by just making a call to this function in a few key places.
Caution: Make sure not to apply this function call multiple times on the same date, as you'll be reapplying the offset multiple times, throwing it off!
Best Solution I have seen from this came from
http://www.codingforums.com/archive/index.php/t-19663.html
Print Time Function
<script language="javascript" type="text/javascript">
//borrowed from echoecho
//http://www.echoecho.com/ubb/viewthread.php?tid=2362&pid=10482&#pid10482
workDate = new Date()
UTCDate = new Date()
UTCDate.setTime(workDate.getTime()+workDate.getTimezoneOffset()*60000)
function printTime(offset) {
offset++;
tempDate = new Date()
tempDate.setTime(UTCDate.getTime()+3600000*(offset))
timeValue = ((tempDate.getHours()<10) ? ("0"+tempDate.getHours()) : (""+tempDate.getHours()))
timeValue += ((tempDate.getMinutes()<10) ? ("0"+tempDate.getMinutes()) : tempDate.getMinutes())
timeValue += " hrs."
return timeValue
}
var now = new Date()
var seed = now.getTime() % 0xfffffff
var same = rand(12)
</script>
Banff, Canada:
<script language="JavaScript">document.write(printTime("-7"))</script>
Full Code Example
<html>
<head>
<script language="javascript" type="text/javascript">
//borrowed from echoecho
//http://www.echoecho.com/ubb/viewthread.php?tid=2362&pid=10482&#pid10482
workDate = new Date()
UTCDate = new Date()
UTCDate.setTime(workDate.getTime()+workDate.getTimezoneOffset()*60000)
function printTime(offset) {
offset++;
tempDate = new Date()
tempDate.setTime(UTCDate.getTime()+3600000*(offset))
timeValue = ((tempDate.getHours()<10) ? ("0"+tempDate.getHours()) : (""+tempDate.getHours()))
timeValue += ((tempDate.getMinutes()<10) ? ("0"+tempDate.getMinutes()) : tempDate.getMinutes())
timeValue += " hrs."
return timeValue
}
var now = new Date()
var seed = now.getTime() % 0xfffffff
var same = rand(12)
</script>
</head>
<body>
Banff, Canada:
<script language="JavaScript">document.write(printTime("-7"))</script>
<br>
Michigan:
<script language="JavaScript">document.write(printTime("-5"))</script>
<br>
Greenwich, England(UTC):
<script language="JavaScript">document.write(printTime("-0"))</script>
<br>
Tokyo, Japan:
<script language="JavaScript">document.write(printTime("+9"))</script>
<br>
Berlin, Germany:
<script language="JavaScript">document.write(printTime("+1"))</script>
</body>
</html>
When I create a date object:
new Date(year, month, day, hour, minute)
I works fine on localhost.
When I deploy to server it breaks, because server is in another timezone.
I can't use getTimezoneOffset(). I need the timezoneOffset of my home - dependent on summertime/wintertime
// add diff minutes between myself (HOME) and server
timezoneHomeOffset (d, tz = 'Europe/Copenhagen') {
const utc = new Date(d.getTime())
const dHome = new Date(d.toLocaleString('en-US', { timeZone: tz }))
const diff = Math.round((utc - dHome) / 60000) // 60*1000 => minutes
d.setMinutes(d.getMinutes() + diff)
return d
}
You can use library to help to change time zone
moment-timezone
var moment = require("moment-timezone");
const today = new Date();
var timeGet = moment(today);
timeGet.tz("Asia/Karachi").format("ha z");
this can change your time zone of your region paste your region area and get real gmt+ resolve issue
For more details visit moment timezone official documentation
This worked fine for different timezones (IST, PST, Mexico, Central America):
let dateUtc: any = new Date(Date.parse(data.details.dateOfBirth));
dateUtc = new Date(dateUtc.getTime() + Math.abs(dateUtc.getTimezoneOffset()*60000));
console.log(dateUtc);
Pain in my brain.
How to get current same date with timezone like on the server with WORDPRESS to js.
var dnow = new Date();
dnow = dnow.getTime() + dnow.getTimezoneOffset()*60*1000 + <?= get_option( 'gmt_offset' ) ?> * 60*60*1000;
First we need to get current date. Then we need to remove user timezone offset. Then we add gmt offset from WordPress option page.
if you want to check the difference in a time between two dates, you can simply check if second timezone is lesser or greater from your first desired timezone and subtract or add a time.
const currTimezone = new Date().getTimezoneOffset(); // your timezone
const newDateTimezone = date.getTimezoneOffset(); // date with unknown timezone
if (currTimezone !== newDateTimezone) {
// and below you are checking if difference should be - or +. It depends on if unknown timezone is lesser or greater than yours
const newTimezone = (currTimezone - newDateTimezone) * (currTimezone > newDateTimezone ? 1 : -1);
date.setTime(date.getTime() + (newTimezone * 60 * 1000));
}
GMT -03:00 Example
new Date(new Date()-3600*1000*3).toISOString(); // 2020-02-27T15:03:26.261Z
Or even
now = new Date().getTime()-3600*1000*3; // 1582818380528
data = new Date(now).toISOString(); // 2020-02-27T15:03:26.261Z
This worked for me. Not sure if it is a good idea though.
var myDate = new Date();
console.log('myDate:', myDate); // myDate: "2018-04-04T01:09:38.112Z"
var offset = '+5'; // e.g. if the timeZone is -5
var MyDateWithOffset = new Date( myDate.toGMTString() + offset );
console.log('MyDateWithOffset:', MyDateWithOffset); // myDateWithOffset: "2018-04-03T20:09:38.000Z"
I used the timezone-js package.
var timezoneJS = require('timezone-js');
var tzdata = require('tzdata');
createDate(dateObj) {
if ( dateObj == null ) {
return null;
}
var nativeTimezoneOffset = new Date().getTimezoneOffset();
var offset = this.getTimeZoneOffset();
// use the native Date object if the timezone matches
if ( offset == -1 * nativeTimezoneOffset ) {
return dateObj;
}
this.loadTimeZones();
// FIXME: it would be better if timezoneJS.Date was an instanceof of Date
// tried jquery $.extend
// added hack to Fiterpickr to look for Dater.getTime instead of "d instanceof Date"
return new timezoneJS.Date(dateObj,this.getTimeZoneName());
},
This is BEST solution
Using:
// TO ALL dates
Date.timezoneOffset(-240) // +4 UTC
// Override offset only for THIS date
new Date().timezoneOffset(-180) // +3 UTC
Code:
Date.prototype.timezoneOffset = new Date().getTimezoneOffset();
Date.setTimezoneOffset = function(timezoneOffset) {
return this.prototype.timezoneOffset = timezoneOffset;
};
Date.getTimezoneOffset = function() {
return this.prototype.timezoneOffset;
};
Date.prototype.setTimezoneOffset = function(timezoneOffset) {
return this.timezoneOffset = timezoneOffset;
};
Date.prototype.getTimezoneOffset = function() {
return this.timezoneOffset;
};
Date.prototype.toString = function() {
var offsetDate, offsetTime;
offsetTime = this.timezoneOffset * 60 * 1000;
offsetDate = new Date(this.getTime() - offsetTime);
return offsetDate.toUTCString();
};
['Milliseconds', 'Seconds', 'Minutes', 'Hours', 'Date', 'Month', 'FullYear', 'Year', 'Day'].forEach((function(_this) {
return function(key) {
Date.prototype["get" + key] = function() {
var offsetDate, offsetTime;
offsetTime = this.timezoneOffset * 60 * 1000;
offsetDate = new Date(this.getTime() - offsetTime);
return offsetDate["getUTC" + key]();
};
return Date.prototype["set" + key] = function(value) {
var offsetDate, offsetTime, time;
offsetTime = this.timezoneOffset * 60 * 1000;
offsetDate = new Date(this.getTime() - offsetTime);
offsetDate["setUTC" + key](value);
time = offsetDate.getTime() + offsetTime;
this.setTime(time);
return time;
};
};
})(this));
Coffee version:
Date.prototype.timezoneOffset = new Date().getTimezoneOffset()
Date.setTimezoneOffset = (timezoneOffset)->
return #prototype.timezoneOffset = timezoneOffset
Date.getTimezoneOffset = ->
return #prototype.timezoneOffset
Date.prototype.setTimezoneOffset = (timezoneOffset)->
return #timezoneOffset = timezoneOffset
Date.prototype.getTimezoneOffset = ->
return #timezoneOffset
Date.prototype.toString = ->
offsetTime = #timezoneOffset * 60 * 1000
offsetDate = new Date(#getTime() - offsetTime)
return offsetDate.toUTCString()
[
'Milliseconds', 'Seconds', 'Minutes', 'Hours',
'Date', 'Month', 'FullYear', 'Year', 'Day'
]
.forEach (key)=>
Date.prototype["get#{key}"] = ->
offsetTime = #timezoneOffset * 60 * 1000
offsetDate = new Date(#getTime() - offsetTime)
return offsetDate["getUTC#{key}"]()
Date.prototype["set#{key}"] = (value)->
offsetTime = #timezoneOffset * 60 * 1000
offsetDate = new Date(#getTime() - offsetTime)
offsetDate["setUTC#{key}"](value)
time = offsetDate.getTime() + offsetTime
#setTime(time)
return time
Related
How can I convert a string to a Date object in JavaScript?
var st = "date in some format"
var dt = new Date();
var dt_st = // st in Date format, same as dt.
The best string format for string parsing is the date ISO format together with the JavaScript Date object constructor.
Examples of ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.
But wait! Just using the "ISO format" doesn't work reliably by itself. String are sometimes parsed as UTC and sometimes as localtime (based on browser vendor and version). The best practice should always be to store dates as UTC and make computations as UTC.
To parse a date as UTC, append a Z - e.g.: new Date('2011-04-11T10:20:30Z').
To display a date in UTC, use .toUTCString(),
to display a date in user's local time, use .toString().
More info on MDN | Date and this answer.
For old Internet Explorer compatibility (IE versions less than 9 do not support ISO format in Date constructor), you should split datetime string representation to it's parts and then you can use constructor using datetime parts, e.g.: new Date('2011', '04' - 1, '11', '11', '51', '00'). Note that the number of the month must be 1 less.
Alternate method - use an appropriate library:
You can also take advantage of the library Moment.js that allows parsing date with the specified time zone.
Unfortunately I found out that
var mydate = new Date('2014-04-03');
console.log(mydate.toDateString());
returns "Wed Apr 02 2014". I know it sounds crazy, but it happens for some users.
The bulletproof solution is the following:
var parts ='2014-04-03'.split('-');
// Please pay attention to the month (parts[1]); JavaScript counts months from 0:
// January - 0, February - 1, etc.
var mydate = new Date(parts[0], parts[1] - 1, parts[2]);
console.log(mydate.toDateString());
var st = "26.04.2013";
var pattern = /(\d{2})\.(\d{2})\.(\d{4})/;
var dt = new Date(st.replace(pattern,'$3-$2-$1'));
And the output will be:
dt => Date {Fri Apr 26 2013}
function stringToDate(_date,_format,_delimiter)
{
var formatLowerCase=_format.toLowerCase();
var formatItems=formatLowerCase.split(_delimiter);
var dateItems=_date.split(_delimiter);
var monthIndex=formatItems.indexOf("mm");
var dayIndex=formatItems.indexOf("dd");
var yearIndex=formatItems.indexOf("yyyy");
var month=parseInt(dateItems[monthIndex]);
month-=1;
var formatedDate = new Date(dateItems[yearIndex],month,dateItems[dayIndex]);
return formatedDate;
}
stringToDate("17/9/2014","dd/MM/yyyy","/");
stringToDate("9/17/2014","mm/dd/yyyy","/")
stringToDate("9-17-2014","mm-dd-yyyy","-")
Recommendation: I recommend to use a package for dates that contains a lot of formats because the timezone and format time management is really a big problem, moment js solve a lot of formats. You could parse easily date from a simple string to date but I think that is a hard work to support all formats and variations of dates.
Update: Moment is now deprecated, A good alternative for moment is datefns https://date-fns.org/
moment.js (http://momentjs.com/) is a complete and good package for use dates and supports ISO 8601 strings.
You could add a string date and format.
moment("12-25-1995", "MM-DD-YYYY");
And you could check if a date is valid.
moment("not a real date").isValid(); //Returns false
Some display examples
let dt = moment("02-01-2019", "MM-DD-YYYY");
console.log(dt.fromNow()+' |'+dt.format('LL'))
// output: "3 months ago | February 1, 2019"
See documentation
http://momentjs.com/docs/#/parsing/string-format/
Pass it as an argument to Date():
var st = "date in some format"
var dt = new Date(st);
You can access the date, month, year using, for example: dt.getMonth().
If you can use the terrific luxon library you can easily parse your date using e.g.
var luxonDate = DateTime.fromISO("2014-09-15T09:00:00");
and can access the JS date object via
luxonDate().toJSDate();
The old answer used MomentJS
var momentDate = moment("2014-09-15 09:00:00");
momentDate ().toDate();
For those who are looking for a tiny and smart solution:
String.prototype.toDate = function(format)
{
var normalized = this.replace(/[^a-zA-Z0-9]/g, '-');
var normalizedFormat= format.toLowerCase().replace(/[^a-zA-Z0-9]/g, '-');
var formatItems = normalizedFormat.split('-');
var dateItems = normalized.split('-');
var monthIndex = formatItems.indexOf("mm");
var dayIndex = formatItems.indexOf("dd");
var yearIndex = formatItems.indexOf("yyyy");
var hourIndex = formatItems.indexOf("hh");
var minutesIndex = formatItems.indexOf("ii");
var secondsIndex = formatItems.indexOf("ss");
var today = new Date();
var year = yearIndex>-1 ? dateItems[yearIndex] : today.getFullYear();
var month = monthIndex>-1 ? dateItems[monthIndex]-1 : today.getMonth()-1;
var day = dayIndex>-1 ? dateItems[dayIndex] : today.getDate();
var hour = hourIndex>-1 ? dateItems[hourIndex] : today.getHours();
var minute = minutesIndex>-1 ? dateItems[minutesIndex] : today.getMinutes();
var second = secondsIndex>-1 ? dateItems[secondsIndex] : today.getSeconds();
return new Date(year,month,day,hour,minute,second);
};
Example:
"22/03/2016 14:03:01".toDate("dd/mm/yyyy hh:ii:ss");
"2016-03-29 18:30:00".toDate("yyyy-mm-dd hh:ii:ss");
Just new Date(st);
Assuming that it's the proper format.
new Date(2000, 10, 1) will give you "Wed Nov 01 2000 00:00:00 GMT+0100 (CET)"
See that 0 for month gives you January
If you want to convert from the format "dd/MM/yyyy". Here is an example:
var pattern = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var arrayDate = stringDate.match(pattern);
var dt = new Date(arrayDate[3], arrayDate[2] - 1, arrayDate[1]);
This solution works in IE versions less than 9.
Timestamps should be casted to a Number
var ts = '1471793029764';
ts = Number(ts); // cast it to a Number
var date = new Date(ts); // works
var invalidDate = new Date('1471793029764'); // does not work. Invalid Date
That's the best and simpler solution in my view:
Just concatenate your date string (using ISO format) with "T00:00:00" in the end and use the JavaScript Date() constructor, like the example below.
const dateString = '2014-04-03'
var mydate = new Date(dateString + "T00:00:00");
console.log(mydate.toDateString());
And just a few details about the solution above (but optional reading):
In ISO format, if you provide time and Z is not present in the end of
string, the date will be local time zone instead of UTC time
zone. That means, when setting a date in this way, without
specifying the time zone, JavaScript will use the local browser's time
zone. And when getting a date, without specifying the time zone
as well, the result is also converted to the browser's time zone. And,
by default, almost every date method in JavaScript (except one)
gives you a date/time in local time zone as well (you only get UTC if
you specify UTC). So, using in local/browser time zone you probably
won't get unwanted results because difference between your
local/browse time zone and the UTC time zone, which is one of the main
complaints with date string conversion. But if you will use this
solution, understand your context and be aware of what you are doing.
And also be careful that omitting T or Z in a date-time string
can give different results in different browsers.
Important to note that the example above will give you exactly the same return to this example below, that is the second most voted answer in this question:
var parts ='2014-04-03'.split('-');
// Please pay attention to the month (parts[1]); JavaScript counts months from 0:
// January - 0, February - 1, etc.
var mydate = new Date(parts[0], parts[1] - 1, parts[2]);
console.log(mydate.toDateString());
The main difference is that the first example provided here is simpler and even more error proof than the second one (at least in my view, as explained below).
Because if you call the JavaScript Date() constructor date with just one date-string argument in ISO format (first example), it doesn't accept values above its logical limit (so, if you give 13 as month or 32 as day, you get Invalid Date).
But when you use the same constructor with multiple date-arguments (second example), parameters above it logical limit will be adjusted to the adjacent value and you won't get Invalid Date Error (so, if you give 13 as month, it will adjust to 1, instead of give you an Invalid Date).
Or an alternative (and third) solution would be mix both, use the first example just to validate the date-string and if it is valid use the second example (so you avoid possible browsers inconsistences of the first example and at the same time avoid the permission of parameters above it logical limit of the second example).
Like so (accepting partial dates as well):
function covertStringToDate(dateString) {
//dateString should be in ISO format: "yyyy-mm-dd", "yyyy-mm" or "yyyy"
if(new Date(dateString).toString() === "Invalid Date") {
return false
} else {
const onlyNumbers = dateString.replace(/\D/g, "");
const year = onlyNumbers.slice(0,4)
const month = onlyNumbers.slice(4,6)
const day = onlyNumbers.slice(6,8)
if(!month){
return(new Date(year))
} else if (!day) {
return(new Date(year, month - 1))
} else {
return(new Date(year, month - 1, day))
}
}
}
And a fourth alternative (and last suggestion) would be to use an appropriate third library (like moment or date-fns)
References:
https://www.w3schools.com/js/js_date_formats.asp
https://css-tricks.com/everything-you-need-to-know-about-date-in-javascript/
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Date#parameters
Date.parse almost gets you what you want. It chokes on the am/pm part, but with some hacking you can get it to work:
var str = 'Sun Apr 25, 2010 3:30pm',
timestamp;
timestamp = Date.parse(str.replace(/[ap]m$/i, ''));
if(str.match(/pm$/i) >= 0) {
timestamp += 12 * 60 * 60 * 1000;
}
Performance
Today (2020.05.08) I perform tests for chosen solutions - for two cases: input date is ISO8601 string (Ad,Bd,Cd,Dd,Ed) and input date is timestamp (At, Ct, Dt). Solutions Bd,Cd,Ct not return js Date object as results, but I add them because they can be useful but I not compare them with valid solutions. This results can be useful for massive date parsing.
Conclusions
Solution new Date (Ad) is 50-100x faster than moment.js (Dd) for all browsers for ISO date and timestamp
Solution new Date (Ad) is ~10x faster than parseDate (Ed)
Solution Date.parse(Bd) is fastest if wee need to get timestamp from ISO date on all browsers
Details
I perform test on MacOs High Sierra 10.13.6 on Chrome 81.0, Safari 13.1, Firefox 75.0. Solution parseDate (Ed) use new Date(0) and manually set UTC date components.
let ds = '2020-05-14T00:00Z'; // Valid ISO8601 UTC date
let ts = +'1589328000000'; // timestamp
let Ad = new Date(ds);
let Bd = Date.parse(ds);
let Cd = moment(ds);
let Dd = moment(ds).toDate();
let Ed = parseDate(ds);
let At = new Date(ts);
let Ct = moment(ts);
let Dt = moment(ts).toDate();
log = (n,d) => console.log(`${n}: ${+d} ${d}`);
console.log('from date string:', ds)
log('Ad', Ad);
log('Bd', Bd);
log('Cd', Cd);
log('Dd', Dd);
log('Ed', Ed);
console.log('from timestamp:', ts)
log('At', At);
log('Ct', Ct);
log('Dt', Dt);
function parseDate(dateStr) {
let [year,month,day] = dateStr.split(' ')[0].split('-');
let d=new Date(0);
d.setUTCFullYear(year);
d.setUTCMonth(month-1);
d.setUTCDate(day)
return d;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment-with-locales.min.js"></script>
This snippet only presents used soultions
Results for chrome
Convert to format pt-BR:
var dateString = "13/10/2014";
var dataSplit = dateString.split('/');
var dateConverted;
if (dataSplit[2].split(" ").length > 1) {
var hora = dataSplit[2].split(" ")[1].split(':');
dataSplit[2] = dataSplit[2].split(" ")[0];
dateConverted = new Date(dataSplit[2], dataSplit[1]-1, dataSplit[0], hora[0], hora[1]);
} else {
dateConverted = new Date(dataSplit[2], dataSplit[1] - 1, dataSplit[0]);
}
I hope help somebody!!!
I have created a fiddle for this, you can use toDate() function on any date string and provide the date format. This will return you a Date object.
https://jsfiddle.net/Sushil231088/q56yd0rp/
"17/9/2014".toDate("dd/MM/yyyy", "/")
For сonverting string to date in js i use http://momentjs.com/
moment().format('MMMM Do YYYY, h:mm:ss a'); // August 16th 2015, 4:17:24 pm
moment().format('dddd'); // Sunday
moment().format("MMM Do YY"); // Aug 16th 15
moment().format('YYYY [escaped] YYYY'); // 2015 escaped 2015
moment("20111031", "YYYYMMDD").fromNow(); // 4 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 3 years ago
moment().startOf('day').fromNow(); // 16 hours ago
moment().endOf('day').fromNow(); // in 8 hours
I made this function to convert any Date object to a UTC Date object.
function dateToUTC(date) {
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}
dateToUTC(new Date());
You Can try this:
function formatDate(userDOB) {
const dob = new Date(userDOB);
const monthNames = [
'January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December'
];
const day = dob.getDate();
const monthIndex = dob.getMonth();
const year = dob.getFullYear();
// return day + ' ' + monthNames[monthIndex] + ' ' + year;
return `${day} ${monthNames[monthIndex]} ${year}`;
}
console.log(formatDate('1982-08-10'));
This answer is based on Kassem's answer but it also handles two-digit years. I submitted an edit to Kassem's answer, but in case it wasn't approved, I'm also submitting this as a separate answer.
function stringToDate(_date,_format,_delimiter) {
var formatLowerCase=_format.toLowerCase();
var formatItems=formatLowerCase.split(_delimiter);
var dateItems=_date.split(_delimiter);
var monthIndex=formatItems.indexOf("mm");
var dayIndex=formatItems.indexOf("dd");
var yearIndex=formatItems.indexOf("yyyy");
var year = parseInt(dateItems[yearIndex]);
// adjust for 2 digit year
if (year < 100) { year += 2000; }
var month=parseInt(dateItems[monthIndex]);
month-=1;
var formatedDate = new Date(year,month,dateItems[dayIndex]);
return formatedDate;
}
stringToDate("17/9/14","dd/MM/yyyy","/");
stringToDate("17/9/2014","dd/MM/yyyy","/");
stringToDate("9/17/2014","mm/dd/yyyy","/")
stringToDate("9-17-2014","mm-dd-yyyy","-")
var date = new Date(year, month, day);
or
var date = new Date('01/01/1970');
date string in format '01-01-1970' will not work in FireFox, So better use "/" instead of "-" in date format string.
Yet another way to do it:
String.prototype.toDate = function(format) {
format = format || "dmy";
var separator = this.match(/[^0-9]/)[0];
var components = this.split(separator);
var day, month, year;
for (var key in format) {
var fmt_value = format[key];
var value = components[key];
switch (fmt_value) {
case "d":
day = parseInt(value);
break;
case "m":
month = parseInt(value)-1;
break;
case "y":
year = parseInt(value);
}
}
return new Date(year, month, day);
};
a = "3/2/2017";
console.log(a.toDate("dmy"));
// Date 2017-02-03T00:00:00.000Z
You can using regex to parse string to detail time then create date or any return format like :
//example : let dateString = "2018-08-17 01:02:03.4"
function strToDate(dateString){
let reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}).(\d{1})/
, [,year, month, day, hours, minutes, seconds, miliseconds] = reggie.exec(dateString)
, dateObject = new Date(year, month-1, day, hours, minutes, seconds, miliseconds);
return dateObject;
}
alert(strToDate(dateString));
If you need to check the contents of the string before converting to Date format:
// Convert 'M/D/YY' to Date()
mdyToDate = function(mdy) {
var d = mdy.split(/[\/\-\.]/, 3);
if (d.length != 3) return null;
// Check if date is valid
var mon = parseInt(d[0]),
day = parseInt(d[1]),
year= parseInt(d[2]);
if (d[2].length == 2) year += 2000;
if (day <= 31 && mon <= 12 && year >= 2015)
return new Date(year, mon - 1, day);
return null;
}
I have created parseDateTime function to convert the string to date object and it is working in all browser (including IE browser), check if anyone required, reference
https://github.com/Umesh-Markande/Parse-String-to-Date-in-all-browser
function parseDateTime(datetime) {
var monthNames = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
if(datetime.split(' ').length == 3){
var date = datetime.split(' ')[0];
var time = datetime.split(' ')[1].replace('.00','');
var timearray = time.split(':');
var hours = parseInt(time.split(':')[0]);
var format = datetime.split(' ')[2];
var bits = date.split(/\D/);
date = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
if ((format === 'PM' || format === 'pm') && hours !== 12) {
hours += 12;
try{ time = hours+':'+timearray[1]+':'+timearray[2] }catch(e){ time = hours+':'+timearray[1] }
}
var formateddatetime = new Date(monthNames[monthIndex] + ' ' + day + ' ' + year + ' ' + time);
return formateddatetime;
}else if(datetime.split(' ').length == 2){
var date = datetime.split(' ')[0];
var time = datetime.split(' ')[1];
var bits = date.split(/\D/);
var datetimevalue = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
var day = datetimevalue.getDate();
var monthIndex = datetimevalue.getMonth();
var year = datetimevalue.getFullYear();
var formateddatetime = new Date(monthNames[monthIndex] + ' ' + day + ' ' + year + ' ' + time);
return formateddatetime;
}else if(datetime != ''){
var bits = datetime.split(/\D/);
var date = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
return date;
}
return datetime;
}
var date1 = '2018-05-14 05:04:22 AM'; // yyyy-mm-dd hh:mm:ss A
var date2 = '2018/05/14 05:04:22 AM'; // yyyy/mm/dd hh:mm:ss A
var date3 = '2018/05/04'; // yyyy/mm/dd
var date4 = '2018-05-04'; // yyyy-mm-dd
var date5 = '2018-05-14 15:04:22'; // yyyy-mm-dd HH:mm:ss
var date6 = '2018/05/14 14:04:22'; // yyyy/mm/dd HH:mm:ss
console.log(parseDateTime(date1))
console.log(parseDateTime(date2))
console.log(parseDateTime(date3))
console.log(parseDateTime(date4))
console.log(parseDateTime(date5))
console.log(parseDateTime(date6))
**Output---**
Mon May 14 2018 05:04:22 GMT+0530 (India Standard Time)
Mon May 14 2018 05:04:22 GMT+0530 (India Standard Time)
Fri May 04 2018 00:00:00 GMT+0530 (India Standard Time)
Fri May 04 2018 00:00:00 GMT+0530 (India Standard Time)
Mon May 14 2018 15:04:22 GMT+0530 (India Standard Time)
Mon May 14 2018 14:04:22 GMT+0530 (India Standard Time)
ISO 8601-esque datestrings, as excellent as the standard is, are still not widely supported.
This is a great resource to figure out which datestring format you should use:
http://dygraphs.com/date-formats.html
Yes, that means that your datestring could be as simple as as opposed to
"2014/10/13 23:57:52"
instead of
"2014-10-13 23:57:52"
//little bit of code for Converting dates
var dat1 = document.getElementById('inputDate').value;
var date1 = new Date(dat1)//converts string to date object
alert(date1);
var dat2 = document.getElementById('inputFinishDate').value;
var date2 = new Date(dat2)
alert(date2);
use this code : (my problem was solved with this code)
function dateDiff(date1, date2){
var diff = {} // Initialisation du retour
var tmp = date2 - date1;
tmp = Math.floor(tmp/1000); // Nombre de secondes entre les 2 dates
diff.sec = tmp % 60; // Extraction du nombre de secondes
tmp = Math.floor((tmp-diff.sec)/60); // Nombre de minutes (partie entière)
diff.min = tmp % 60; // Extraction du nombre de minutes
tmp = Math.floor((tmp-diff.min)/60); // Nombre d'heures (entières)
diff.hour = tmp % 24; // Extraction du nombre d'heures
tmp = Math.floor((tmp-diff.hour)/24); // Nombre de jours restants
diff.day = tmp;
return diff;
}
I wrote a reusable function that i use when i get date strings from the server.
you can pass your desired delimiter( / - etc..) that separates the day month and year in order to use the split() method.
you can see & test it on this working example.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<div>
<span>day:
</span>
<span id='day'>
</span>
</div>
<div>
<span>month:
</span>
<span id='month'>
</span>
</div>
<div>
<span>year:
</span>
<span id='year'>
</span>
</div>
<br/>
<input type="button" id="" value="convert" onClick="convert('/','28/10/1980')"/>
<span>28/10/1980
</span>
<script>
function convert(delimiter,dateString)
{
var splitted = dateString.split('/');
// create a new date from the splitted string
var myDate = new Date(splitted[2],splitted[1],splitted[0]);
// now you can access the Date and use its methods
document.getElementById('day').innerHTML = myDate.getDate();
document.getElementById('month').innerHTML = myDate.getMonth();
document.getElementById('year').innerHTML = myDate.getFullYear();
}
</script>
</body>
</html>
How can I convert a string to a Date object in JavaScript?
var st = "date in some format"
var dt = new Date();
var dt_st = // st in Date format, same as dt.
The best string format for string parsing is the date ISO format together with the JavaScript Date object constructor.
Examples of ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.
But wait! Just using the "ISO format" doesn't work reliably by itself. String are sometimes parsed as UTC and sometimes as localtime (based on browser vendor and version). The best practice should always be to store dates as UTC and make computations as UTC.
To parse a date as UTC, append a Z - e.g.: new Date('2011-04-11T10:20:30Z').
To display a date in UTC, use .toUTCString(),
to display a date in user's local time, use .toString().
More info on MDN | Date and this answer.
For old Internet Explorer compatibility (IE versions less than 9 do not support ISO format in Date constructor), you should split datetime string representation to it's parts and then you can use constructor using datetime parts, e.g.: new Date('2011', '04' - 1, '11', '11', '51', '00'). Note that the number of the month must be 1 less.
Alternate method - use an appropriate library:
You can also take advantage of the library Moment.js that allows parsing date with the specified time zone.
Unfortunately I found out that
var mydate = new Date('2014-04-03');
console.log(mydate.toDateString());
returns "Wed Apr 02 2014". I know it sounds crazy, but it happens for some users.
The bulletproof solution is the following:
var parts ='2014-04-03'.split('-');
// Please pay attention to the month (parts[1]); JavaScript counts months from 0:
// January - 0, February - 1, etc.
var mydate = new Date(parts[0], parts[1] - 1, parts[2]);
console.log(mydate.toDateString());
var st = "26.04.2013";
var pattern = /(\d{2})\.(\d{2})\.(\d{4})/;
var dt = new Date(st.replace(pattern,'$3-$2-$1'));
And the output will be:
dt => Date {Fri Apr 26 2013}
function stringToDate(_date,_format,_delimiter)
{
var formatLowerCase=_format.toLowerCase();
var formatItems=formatLowerCase.split(_delimiter);
var dateItems=_date.split(_delimiter);
var monthIndex=formatItems.indexOf("mm");
var dayIndex=formatItems.indexOf("dd");
var yearIndex=formatItems.indexOf("yyyy");
var month=parseInt(dateItems[monthIndex]);
month-=1;
var formatedDate = new Date(dateItems[yearIndex],month,dateItems[dayIndex]);
return formatedDate;
}
stringToDate("17/9/2014","dd/MM/yyyy","/");
stringToDate("9/17/2014","mm/dd/yyyy","/")
stringToDate("9-17-2014","mm-dd-yyyy","-")
Recommendation: I recommend to use a package for dates that contains a lot of formats because the timezone and format time management is really a big problem, moment js solve a lot of formats. You could parse easily date from a simple string to date but I think that is a hard work to support all formats and variations of dates.
Update: Moment is now deprecated, A good alternative for moment is datefns https://date-fns.org/
moment.js (http://momentjs.com/) is a complete and good package for use dates and supports ISO 8601 strings.
You could add a string date and format.
moment("12-25-1995", "MM-DD-YYYY");
And you could check if a date is valid.
moment("not a real date").isValid(); //Returns false
Some display examples
let dt = moment("02-01-2019", "MM-DD-YYYY");
console.log(dt.fromNow()+' |'+dt.format('LL'))
// output: "3 months ago | February 1, 2019"
See documentation
http://momentjs.com/docs/#/parsing/string-format/
Pass it as an argument to Date():
var st = "date in some format"
var dt = new Date(st);
You can access the date, month, year using, for example: dt.getMonth().
If you can use the terrific luxon library you can easily parse your date using e.g.
var luxonDate = DateTime.fromISO("2014-09-15T09:00:00");
and can access the JS date object via
luxonDate().toJSDate();
The old answer used MomentJS
var momentDate = moment("2014-09-15 09:00:00");
momentDate ().toDate();
For those who are looking for a tiny and smart solution:
String.prototype.toDate = function(format)
{
var normalized = this.replace(/[^a-zA-Z0-9]/g, '-');
var normalizedFormat= format.toLowerCase().replace(/[^a-zA-Z0-9]/g, '-');
var formatItems = normalizedFormat.split('-');
var dateItems = normalized.split('-');
var monthIndex = formatItems.indexOf("mm");
var dayIndex = formatItems.indexOf("dd");
var yearIndex = formatItems.indexOf("yyyy");
var hourIndex = formatItems.indexOf("hh");
var minutesIndex = formatItems.indexOf("ii");
var secondsIndex = formatItems.indexOf("ss");
var today = new Date();
var year = yearIndex>-1 ? dateItems[yearIndex] : today.getFullYear();
var month = monthIndex>-1 ? dateItems[monthIndex]-1 : today.getMonth()-1;
var day = dayIndex>-1 ? dateItems[dayIndex] : today.getDate();
var hour = hourIndex>-1 ? dateItems[hourIndex] : today.getHours();
var minute = minutesIndex>-1 ? dateItems[minutesIndex] : today.getMinutes();
var second = secondsIndex>-1 ? dateItems[secondsIndex] : today.getSeconds();
return new Date(year,month,day,hour,minute,second);
};
Example:
"22/03/2016 14:03:01".toDate("dd/mm/yyyy hh:ii:ss");
"2016-03-29 18:30:00".toDate("yyyy-mm-dd hh:ii:ss");
Just new Date(st);
Assuming that it's the proper format.
new Date(2000, 10, 1) will give you "Wed Nov 01 2000 00:00:00 GMT+0100 (CET)"
See that 0 for month gives you January
If you want to convert from the format "dd/MM/yyyy". Here is an example:
var pattern = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var arrayDate = stringDate.match(pattern);
var dt = new Date(arrayDate[3], arrayDate[2] - 1, arrayDate[1]);
This solution works in IE versions less than 9.
Timestamps should be casted to a Number
var ts = '1471793029764';
ts = Number(ts); // cast it to a Number
var date = new Date(ts); // works
var invalidDate = new Date('1471793029764'); // does not work. Invalid Date
That's the best and simpler solution in my view:
Just concatenate your date string (using ISO format) with "T00:00:00" in the end and use the JavaScript Date() constructor, like the example below.
const dateString = '2014-04-03'
var mydate = new Date(dateString + "T00:00:00");
console.log(mydate.toDateString());
And just a few details about the solution above (but optional reading):
In ISO format, if you provide time and Z is not present in the end of
string, the date will be local time zone instead of UTC time
zone. That means, when setting a date in this way, without
specifying the time zone, JavaScript will use the local browser's time
zone. And when getting a date, without specifying the time zone
as well, the result is also converted to the browser's time zone. And,
by default, almost every date method in JavaScript (except one)
gives you a date/time in local time zone as well (you only get UTC if
you specify UTC). So, using in local/browser time zone you probably
won't get unwanted results because difference between your
local/browse time zone and the UTC time zone, which is one of the main
complaints with date string conversion. But if you will use this
solution, understand your context and be aware of what you are doing.
And also be careful that omitting T or Z in a date-time string
can give different results in different browsers.
Important to note that the example above will give you exactly the same return to this example below, that is the second most voted answer in this question:
var parts ='2014-04-03'.split('-');
// Please pay attention to the month (parts[1]); JavaScript counts months from 0:
// January - 0, February - 1, etc.
var mydate = new Date(parts[0], parts[1] - 1, parts[2]);
console.log(mydate.toDateString());
The main difference is that the first example provided here is simpler and even more error proof than the second one (at least in my view, as explained below).
Because if you call the JavaScript Date() constructor date with just one date-string argument in ISO format (first example), it doesn't accept values above its logical limit (so, if you give 13 as month or 32 as day, you get Invalid Date).
But when you use the same constructor with multiple date-arguments (second example), parameters above it logical limit will be adjusted to the adjacent value and you won't get Invalid Date Error (so, if you give 13 as month, it will adjust to 1, instead of give you an Invalid Date).
Or an alternative (and third) solution would be mix both, use the first example just to validate the date-string and if it is valid use the second example (so you avoid possible browsers inconsistences of the first example and at the same time avoid the permission of parameters above it logical limit of the second example).
Like so (accepting partial dates as well):
function covertStringToDate(dateString) {
//dateString should be in ISO format: "yyyy-mm-dd", "yyyy-mm" or "yyyy"
if(new Date(dateString).toString() === "Invalid Date") {
return false
} else {
const onlyNumbers = dateString.replace(/\D/g, "");
const year = onlyNumbers.slice(0,4)
const month = onlyNumbers.slice(4,6)
const day = onlyNumbers.slice(6,8)
if(!month){
return(new Date(year))
} else if (!day) {
return(new Date(year, month - 1))
} else {
return(new Date(year, month - 1, day))
}
}
}
And a fourth alternative (and last suggestion) would be to use an appropriate third library (like moment or date-fns)
References:
https://www.w3schools.com/js/js_date_formats.asp
https://css-tricks.com/everything-you-need-to-know-about-date-in-javascript/
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Date#parameters
Date.parse almost gets you what you want. It chokes on the am/pm part, but with some hacking you can get it to work:
var str = 'Sun Apr 25, 2010 3:30pm',
timestamp;
timestamp = Date.parse(str.replace(/[ap]m$/i, ''));
if(str.match(/pm$/i) >= 0) {
timestamp += 12 * 60 * 60 * 1000;
}
Performance
Today (2020.05.08) I perform tests for chosen solutions - for two cases: input date is ISO8601 string (Ad,Bd,Cd,Dd,Ed) and input date is timestamp (At, Ct, Dt). Solutions Bd,Cd,Ct not return js Date object as results, but I add them because they can be useful but I not compare them with valid solutions. This results can be useful for massive date parsing.
Conclusions
Solution new Date (Ad) is 50-100x faster than moment.js (Dd) for all browsers for ISO date and timestamp
Solution new Date (Ad) is ~10x faster than parseDate (Ed)
Solution Date.parse(Bd) is fastest if wee need to get timestamp from ISO date on all browsers
Details
I perform test on MacOs High Sierra 10.13.6 on Chrome 81.0, Safari 13.1, Firefox 75.0. Solution parseDate (Ed) use new Date(0) and manually set UTC date components.
let ds = '2020-05-14T00:00Z'; // Valid ISO8601 UTC date
let ts = +'1589328000000'; // timestamp
let Ad = new Date(ds);
let Bd = Date.parse(ds);
let Cd = moment(ds);
let Dd = moment(ds).toDate();
let Ed = parseDate(ds);
let At = new Date(ts);
let Ct = moment(ts);
let Dt = moment(ts).toDate();
log = (n,d) => console.log(`${n}: ${+d} ${d}`);
console.log('from date string:', ds)
log('Ad', Ad);
log('Bd', Bd);
log('Cd', Cd);
log('Dd', Dd);
log('Ed', Ed);
console.log('from timestamp:', ts)
log('At', At);
log('Ct', Ct);
log('Dt', Dt);
function parseDate(dateStr) {
let [year,month,day] = dateStr.split(' ')[0].split('-');
let d=new Date(0);
d.setUTCFullYear(year);
d.setUTCMonth(month-1);
d.setUTCDate(day)
return d;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment-with-locales.min.js"></script>
This snippet only presents used soultions
Results for chrome
Convert to format pt-BR:
var dateString = "13/10/2014";
var dataSplit = dateString.split('/');
var dateConverted;
if (dataSplit[2].split(" ").length > 1) {
var hora = dataSplit[2].split(" ")[1].split(':');
dataSplit[2] = dataSplit[2].split(" ")[0];
dateConverted = new Date(dataSplit[2], dataSplit[1]-1, dataSplit[0], hora[0], hora[1]);
} else {
dateConverted = new Date(dataSplit[2], dataSplit[1] - 1, dataSplit[0]);
}
I hope help somebody!!!
I have created a fiddle for this, you can use toDate() function on any date string and provide the date format. This will return you a Date object.
https://jsfiddle.net/Sushil231088/q56yd0rp/
"17/9/2014".toDate("dd/MM/yyyy", "/")
For сonverting string to date in js i use http://momentjs.com/
moment().format('MMMM Do YYYY, h:mm:ss a'); // August 16th 2015, 4:17:24 pm
moment().format('dddd'); // Sunday
moment().format("MMM Do YY"); // Aug 16th 15
moment().format('YYYY [escaped] YYYY'); // 2015 escaped 2015
moment("20111031", "YYYYMMDD").fromNow(); // 4 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 3 years ago
moment().startOf('day').fromNow(); // 16 hours ago
moment().endOf('day').fromNow(); // in 8 hours
I made this function to convert any Date object to a UTC Date object.
function dateToUTC(date) {
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}
dateToUTC(new Date());
You Can try this:
function formatDate(userDOB) {
const dob = new Date(userDOB);
const monthNames = [
'January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December'
];
const day = dob.getDate();
const monthIndex = dob.getMonth();
const year = dob.getFullYear();
// return day + ' ' + monthNames[monthIndex] + ' ' + year;
return `${day} ${monthNames[monthIndex]} ${year}`;
}
console.log(formatDate('1982-08-10'));
This answer is based on Kassem's answer but it also handles two-digit years. I submitted an edit to Kassem's answer, but in case it wasn't approved, I'm also submitting this as a separate answer.
function stringToDate(_date,_format,_delimiter) {
var formatLowerCase=_format.toLowerCase();
var formatItems=formatLowerCase.split(_delimiter);
var dateItems=_date.split(_delimiter);
var monthIndex=formatItems.indexOf("mm");
var dayIndex=formatItems.indexOf("dd");
var yearIndex=formatItems.indexOf("yyyy");
var year = parseInt(dateItems[yearIndex]);
// adjust for 2 digit year
if (year < 100) { year += 2000; }
var month=parseInt(dateItems[monthIndex]);
month-=1;
var formatedDate = new Date(year,month,dateItems[dayIndex]);
return formatedDate;
}
stringToDate("17/9/14","dd/MM/yyyy","/");
stringToDate("17/9/2014","dd/MM/yyyy","/");
stringToDate("9/17/2014","mm/dd/yyyy","/")
stringToDate("9-17-2014","mm-dd-yyyy","-")
var date = new Date(year, month, day);
or
var date = new Date('01/01/1970');
date string in format '01-01-1970' will not work in FireFox, So better use "/" instead of "-" in date format string.
Yet another way to do it:
String.prototype.toDate = function(format) {
format = format || "dmy";
var separator = this.match(/[^0-9]/)[0];
var components = this.split(separator);
var day, month, year;
for (var key in format) {
var fmt_value = format[key];
var value = components[key];
switch (fmt_value) {
case "d":
day = parseInt(value);
break;
case "m":
month = parseInt(value)-1;
break;
case "y":
year = parseInt(value);
}
}
return new Date(year, month, day);
};
a = "3/2/2017";
console.log(a.toDate("dmy"));
// Date 2017-02-03T00:00:00.000Z
You can using regex to parse string to detail time then create date or any return format like :
//example : let dateString = "2018-08-17 01:02:03.4"
function strToDate(dateString){
let reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}).(\d{1})/
, [,year, month, day, hours, minutes, seconds, miliseconds] = reggie.exec(dateString)
, dateObject = new Date(year, month-1, day, hours, minutes, seconds, miliseconds);
return dateObject;
}
alert(strToDate(dateString));
If you need to check the contents of the string before converting to Date format:
// Convert 'M/D/YY' to Date()
mdyToDate = function(mdy) {
var d = mdy.split(/[\/\-\.]/, 3);
if (d.length != 3) return null;
// Check if date is valid
var mon = parseInt(d[0]),
day = parseInt(d[1]),
year= parseInt(d[2]);
if (d[2].length == 2) year += 2000;
if (day <= 31 && mon <= 12 && year >= 2015)
return new Date(year, mon - 1, day);
return null;
}
I have created parseDateTime function to convert the string to date object and it is working in all browser (including IE browser), check if anyone required, reference
https://github.com/Umesh-Markande/Parse-String-to-Date-in-all-browser
function parseDateTime(datetime) {
var monthNames = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
if(datetime.split(' ').length == 3){
var date = datetime.split(' ')[0];
var time = datetime.split(' ')[1].replace('.00','');
var timearray = time.split(':');
var hours = parseInt(time.split(':')[0]);
var format = datetime.split(' ')[2];
var bits = date.split(/\D/);
date = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
if ((format === 'PM' || format === 'pm') && hours !== 12) {
hours += 12;
try{ time = hours+':'+timearray[1]+':'+timearray[2] }catch(e){ time = hours+':'+timearray[1] }
}
var formateddatetime = new Date(monthNames[monthIndex] + ' ' + day + ' ' + year + ' ' + time);
return formateddatetime;
}else if(datetime.split(' ').length == 2){
var date = datetime.split(' ')[0];
var time = datetime.split(' ')[1];
var bits = date.split(/\D/);
var datetimevalue = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
var day = datetimevalue.getDate();
var monthIndex = datetimevalue.getMonth();
var year = datetimevalue.getFullYear();
var formateddatetime = new Date(monthNames[monthIndex] + ' ' + day + ' ' + year + ' ' + time);
return formateddatetime;
}else if(datetime != ''){
var bits = datetime.split(/\D/);
var date = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
return date;
}
return datetime;
}
var date1 = '2018-05-14 05:04:22 AM'; // yyyy-mm-dd hh:mm:ss A
var date2 = '2018/05/14 05:04:22 AM'; // yyyy/mm/dd hh:mm:ss A
var date3 = '2018/05/04'; // yyyy/mm/dd
var date4 = '2018-05-04'; // yyyy-mm-dd
var date5 = '2018-05-14 15:04:22'; // yyyy-mm-dd HH:mm:ss
var date6 = '2018/05/14 14:04:22'; // yyyy/mm/dd HH:mm:ss
console.log(parseDateTime(date1))
console.log(parseDateTime(date2))
console.log(parseDateTime(date3))
console.log(parseDateTime(date4))
console.log(parseDateTime(date5))
console.log(parseDateTime(date6))
**Output---**
Mon May 14 2018 05:04:22 GMT+0530 (India Standard Time)
Mon May 14 2018 05:04:22 GMT+0530 (India Standard Time)
Fri May 04 2018 00:00:00 GMT+0530 (India Standard Time)
Fri May 04 2018 00:00:00 GMT+0530 (India Standard Time)
Mon May 14 2018 15:04:22 GMT+0530 (India Standard Time)
Mon May 14 2018 14:04:22 GMT+0530 (India Standard Time)
ISO 8601-esque datestrings, as excellent as the standard is, are still not widely supported.
This is a great resource to figure out which datestring format you should use:
http://dygraphs.com/date-formats.html
Yes, that means that your datestring could be as simple as as opposed to
"2014/10/13 23:57:52"
instead of
"2014-10-13 23:57:52"
//little bit of code for Converting dates
var dat1 = document.getElementById('inputDate').value;
var date1 = new Date(dat1)//converts string to date object
alert(date1);
var dat2 = document.getElementById('inputFinishDate').value;
var date2 = new Date(dat2)
alert(date2);
use this code : (my problem was solved with this code)
function dateDiff(date1, date2){
var diff = {} // Initialisation du retour
var tmp = date2 - date1;
tmp = Math.floor(tmp/1000); // Nombre de secondes entre les 2 dates
diff.sec = tmp % 60; // Extraction du nombre de secondes
tmp = Math.floor((tmp-diff.sec)/60); // Nombre de minutes (partie entière)
diff.min = tmp % 60; // Extraction du nombre de minutes
tmp = Math.floor((tmp-diff.min)/60); // Nombre d'heures (entières)
diff.hour = tmp % 24; // Extraction du nombre d'heures
tmp = Math.floor((tmp-diff.hour)/24); // Nombre de jours restants
diff.day = tmp;
return diff;
}
I wrote a reusable function that i use when i get date strings from the server.
you can pass your desired delimiter( / - etc..) that separates the day month and year in order to use the split() method.
you can see & test it on this working example.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<div>
<span>day:
</span>
<span id='day'>
</span>
</div>
<div>
<span>month:
</span>
<span id='month'>
</span>
</div>
<div>
<span>year:
</span>
<span id='year'>
</span>
</div>
<br/>
<input type="button" id="" value="convert" onClick="convert('/','28/10/1980')"/>
<span>28/10/1980
</span>
<script>
function convert(delimiter,dateString)
{
var splitted = dateString.split('/');
// create a new date from the splitted string
var myDate = new Date(splitted[2],splitted[1],splitted[0]);
// now you can access the Date and use its methods
document.getElementById('day').innerHTML = myDate.getDate();
document.getElementById('month').innerHTML = myDate.getMonth();
document.getElementById('year').innerHTML = myDate.getFullYear();
}
</script>
</body>
</html>
I am looking for a function to convert date in one timezone to another.
It need two parameters,
date (in format "2012/04/10 10:10:30 +0000")
timezone string ("Asia/Jakarta")
The timezone string is described in http://en.wikipedia.org/wiki/Zone.tab
Is there an easy way to do this?
Here is the one-liner:
function convertTZ(date, tzString) {
return new Date((typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", {timeZone: tzString}));
}
// usage: Asia/Jakarta is GMT+7
convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta") // Tue Apr 20 2012 17:10:30 GMT+0700 (Western Indonesia Time)
// Resulting value is regular Date() object
const convertedDate = convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta")
convertedDate.getHours(); // 17
// Bonus: You can also put Date object to first arg
const date = new Date()
convertTZ(date, "Asia/Jakarta") // current date-time in jakarta.
This is the MDN Reference.
Beware the caveat: function above works by relying on parsing toLocaleString result, which is string of a date formatted in en-US locale , e.g. "4/20/2012, 5:10:30 PM". Each browser may not accept en-US formatted date string to its Date constructor and it may return unexpected result (it may ignore daylight saving).
Currently all modern browser accept this format and calculates daylight saving correctly, it may not work on older browser and/or exotic browser.
side-note: It would be great if modern browser have toLocaleDate
function, so we don't have to use this hacky work around.
For moment.js users, you can now use moment-timezone. Using it, your function would look something like this:
function toTimeZone(time, zone) {
var format = 'YYYY/MM/DD HH:mm:ss ZZ';
return moment(time, format).tz(zone).format(format);
}
Most browsers support the toLocaleString function with arguments, older browsers usually ignore the arguments.
const str = new Date().toLocaleString('en-US', { timeZone: 'Asia/Jakarta' });
console.log(str);
Stolen shamelessly from: http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/6016329
/**
* function to calculate local time
* in a different city
* given the city's UTC offset
*/
function calcTime(city, offset) {
// create Date object for current location
var d = new Date();
// get UTC time in msec
var utc = d.getTime();
// create new Date object for different city
// using supplied offset
var nd = new Date(utc + (3600000*offset));
// return time as a string
return "The local time in " + city + " is " + nd.toLocaleString();
}
this function is useful to calculate time zone value by providing name of a city/country and offset value
Okay, found it!
I'm using timezone-js. this is the code:
var dt = new timezoneJS.Date("2012/04/10 10:10:30 +0000", 'Europe/London');
dt.setTimezone("Asia/Jakarta");
console.debug(dt); //return formatted date-time in asia/jakarta
If you don't want to import some big library you could just use Intl.DateTimeFormat to convert Date objects to different timezones.
// Specifying timeZone is what causes the conversion, the rest is just formatting
const options = {
year: '2-digit', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit',
timeZone: 'Asia/Jakarta',
timeZoneName: 'short'
}
const formatter = new Intl.DateTimeFormat('sv-SE', options)
const startingDate = new Date("2012/04/10 10:10:30 +0000")
const dateInNewTimezone = formatter.format(startingDate)
console.log(dateInNewTimezone) // 12-04-10 17:10:30 GMT+7
Offsets, daylight saving, and changes in the past will be taken care of for you.
UPDATE
There is also this new Temporal tool that handles timezones among other things. Like only dates or only time. It's experimental as of now
It's meant to replace the old legacy Date
var isoDate = new Date().toJSON() // eg: '2022-11-18T13:56:09.697Z'
Temporal.Instant.from(isoDate).toZonedDateTimeISO('Europe/Stockholm')
Got it!
Wanted to force the date shown = server date, no mattter the local settings (UTC).
My server is GMT-6 --> new Date().getTimezoneOffset() = 360
myTZO = 360;
myNewDate = new Date(myOldDateObj.getTime() + (60000*(myOldDateObj.getTimezoneOffset()-myTZO)));
alert(myNewDate);
You can use to toLocaleString() method for setting the timezone.
new Date().toLocaleString('en-US', { timeZone: 'Indian/Christmas' })
For India you can use "Indian/Christmas" and the following are the various timeZones,
"Antarctica/Davis",
"Asia/Bangkok",
"Asia/Hovd",
"Asia/Jakarta",
"Asia/Phnom_Penh",
"Asia/Pontianak",
"Asia/Saigon",
"Asia/Vientiane",
"Etc/GMT-7",
"Indian/Christmas"
I should note that I am restricted with respect to which external libraries that I can use. moment.js and timezone-js were NOT an option for me.
The js date object that I have is in UTC. I needed to get the date AND time from this date in a specific timezone('America/Chicago' in my case).
var currentUtcTime = new Date(); // This is in UTC
// Converts the UTC time to a locale specific format, including adjusting for timezone.
var currentDateTimeCentralTimeZone = new Date(currentUtcTime.toLocaleString('en-US', { timeZone: 'America/Chicago' }));
console.log('currentUtcTime: ' + currentUtcTime.toLocaleDateString());
console.log('currentUtcTime Hour: ' + currentUtcTime.getHours());
console.log('currentUtcTime Minute: ' + currentUtcTime.getMinutes());
console.log('currentDateTimeCentralTimeZone: ' + currentDateTimeCentralTimeZone.toLocaleDateString());
console.log('currentDateTimeCentralTimeZone Hour: ' + currentDateTimeCentralTimeZone.getHours());
console.log('currentDateTimeCentralTimeZone Minute: ' + currentDateTimeCentralTimeZone.getMinutes());
UTC is currently 6 hours ahead of 'America/Chicago'. Output is:
currentUtcTime: 11/25/2016
currentUtcTime Hour: 16
currentUtcTime Minute: 15
currentDateTimeCentralTimeZone: 11/25/2016
currentDateTimeCentralTimeZone Hour: 10
currentDateTimeCentralTimeZone Minute: 15
If you just need to convert timezones I have uploaded a stripped-down version of moment-timezone with just the bare minimum functionallity. Its ~1KB + data:
S.loadData({
"zones": [
"Europe/Paris|CET CEST|-10 -20|01010101010101010101010|1GNB0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0|11e6",
"Australia/Sydney|AEDT AEST|-b0 -a0|01010101010101010101010|1GQg0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0|40e5",
],
"links": [
"Europe/Paris|Europe/Madrid",
]
});
let d = new Date();
console.log(S.tz(d, "Europe/Madrid").toLocaleString());
console.log(S.tz(d, "Australia/Sydney").toLocaleString());
Here is my code, it is working perfectly, you can try with give below demo:
$(document).ready(function() {
//EST
setInterval( function() {
var estTime = new Date();
var currentDateTimeCentralTimeZone = new Date(estTime.toLocaleString('en-US', { timeZone: 'America/Chicago' }));
var seconds = currentDateTimeCentralTimeZone.getSeconds();
var minutes = currentDateTimeCentralTimeZone.getMinutes();
var hours = currentDateTimeCentralTimeZone.getHours()+1;//new Date().getHours();
var am_pm = currentDateTimeCentralTimeZone.getHours() >= 12 ? "PM" : "AM";
if (hours < 10){
hours = "0" + hours;
}
if (minutes < 10){
minutes = "0" + minutes;
}
if (seconds < 10){
seconds = "0" + seconds;
}
var mid='PM';
if(hours==0){ //At 00 hours we need to show 12 am
hours=12;
}
else if(hours>12)
{
hours=hours%12;
mid='AM';
}
var x3 = hours+':'+minutes+':'+seconds +' '+am_pm
// Add a leading zero to seconds value
$("#sec").html(x3);
},1000);
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<p class="date_time"><strong id="sec"></strong></p>
</body>
</html>
Set a variable with year, month, and day separated with - symbols, plus a T and the time in HH:mm:ss pattern, followed by +01:00 at the end of the string (in my case the time zone is +1). Then use this string as the argument for the date constructor.
// desired format: 2001-02-04T08:16:32+01:00
dateAndTime = year+"-"+month+"-"+day+"T"+hour+":"+minutes+":00+01:00";
var date = new Date(dateAndTime );
Using luxon library:
import { DateTime } from "luxon";
// Convert function:
const convertTz = (datetime, fromTz, toTz, format='yyyy-MM-dd HH:mm:ss') => {
return DateTime.fromFormat(datetime, format, { zone: fromTz }).setZone(toTz).toFormat(format);
}
// Use it like this:
console.log(convertTz('2021-10-03 19:00:00', 'Europe/Lisbon', 'America/New_York'));
You can also use
https://www.npmjs.com/package/ctoc_timezone
It has got much simple implementation and format customisation.
Changing format in toTimeZone:
CtoC.toTimeZone(new Date(),"EST","Do MMM YYYY hh:mm:ss #{EST}");
Output :
28th Feb 2013 19:00:00 EST
You can explore multiple functionalities in the doc.
You can use Intl.DateTimeFormat to specify timezone as an option and it would convert the date or time to your desired timezone.
let timezone = "Asia/Jakarta";
let date = new Date("2012/04/10 10:10:30 +0000");
let formattedDate = new Intl.DateTimeFormat("en-US", { dateStyle: "long" , timeStyle: "short", timeZone: timezone}).format(date);
You can try this also for convert date timezone to India:
var indianTimeZoneVal = new Date().toLocaleString('en-US', {timeZone: 'Asia/Kolkata'});
var indainDateObj = new Date(indianTimeZoneVal);
indainDateObj.setHours(indainDateObj.getHours() + 5);
indainDateObj.setMinutes(indainDateObj.getMinutes() + 30);
console.log(indainDateObj);
I recently did this in Typescript :
// fromTimezone example : Europe/Paris, toTimezone example: Europe/London
private calcTime( fromTimezone: string, toTimezone: string, dateFromTimezone: Date ): Date {
const dateToGetOffset = new Date( 2018, 5, 1, 12 );
const fromTimeString = dateToGetOffset.toLocaleTimeString( "en-UK", { timeZone: fromTimezone, hour12: false } );
const toTimeString = dateToGetOffset.toLocaleTimeString( "en-UK", { timeZone: toTimezone, hour12: false } );
const fromTimeHours: number = parseInt( fromTimeString.substr( 0, 2 ), 10 );
const toTimeHours: number = parseInt( toTimeString.substr( 0, 2 ), 10 );
const offset: number = fromTimeHours - toTimeHours;
// convert to msec
// add local time zone offset
// get UTC time in msec
const dateFromTimezoneUTC = Date.UTC( dateFromTimezone.getUTCFullYear(),
dateFromTimezone.getUTCMonth(),
dateFromTimezone.getUTCDate(),
dateFromTimezone.getUTCHours(),
dateFromTimezone.getUTCMinutes(),
dateFromTimezone.getUTCSeconds(),
);
// create new Date object for different city
// using supplied offset
const dateUTC = new Date( dateFromTimezoneUTC + ( 3600000 * offset ) );
// return time as a string
return dateUTC;
}
I Use "en-UK" format because it is a simple one. Could have been "en-US" or whatever works.
If first argument is your locale timezone and seconde is your target timezone it returns a Date object with the correct offset.
Having looked around a lot including links from this page i found this great article, using moment timezone:
https://www.webniraj.com/2016/11/23/javascript-using-moment-js-to-display-dates-times-in-users-timezone/
To summarise it:
Get the user's timezone
var tz = moment.tz.guess();
console.info('Timezone: ' + tz);
Returns eg: Timezone: Europe/London
Set the default user timezone
moment.tz.setDefault(tz);
Set custom timezone
moment.tz.setDefault('America/Los_Angeles');
Convert date / time to local timezone, assumes original date/time is in UTC
moment.utc('2016-12-25 07:00').tz(tz).format('ddd, Do MMMM YYYY, h:mma');
Returns: Sun, 25th December 2016, 7:00am
Convert date/time to LA Time
moment.utc('2016-12-25 07:00').tz('America/Los_Angeles').format('ddd, Do MMMM YYYY, h:mma');
Returns: Sat, 24th December 2016, 11:00pm
Convert from LA time to London
moment.tz('2016-12-25 07:00', 'America/Los_Angeles').tz('Europe/London').format( 'ddd, Do MMMM YYYY, h:mma' );
Returns: Sun, 25th December 2016, 3:00pm
Provide the desired time zone, for example "Asia/Tehran" to change the current time to that timezone. I used "Asia/Seoul".
You can use the following codes. change the style if you need to do so.
please keep in mind that if you want to have h:m:s format instead of HH:MM:SS, you'll have to remove "function kcwcheckT(i)".
function kcwcheckT(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function kcwt() {
var d = new Date().toLocaleString("en-US", {timeZone: "Asia/Seoul"});
d = new Date(d);
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
h = kcwcheckT(h);
m = kcwcheckT(m);
s = kcwcheckT(s);
document.getElementById("kcwcurtime").innerHTML = h + ":" + m + ":" + s;
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
document.getElementById("kcwcurday").innerHTML = days[d.getDay()]
}
kcwt();
window.setInterval(kcwt, 1000);
#import url('https://fonts.googleapis.com/css2?family=Nunito&display=swap');
.kcwsource {color:#040505;cursor: pointer;display:block;width: 100%;border: none;border-radius:5px;text-align:center;padding: 5px 10px 5px 10px;}
.kcwsource p {font-family: 'Nunito', sans-serif;}
.CurTbx {color:#040505;cursor: pointer;display:block;width: 100%;border: none;border-radius:5px;text-align:center;padding: 5px 10px 5px 10px;}
.kcwcstyle {font-family: 'Nunito', sans-serif; font-size: 22px;display: inline-block;}
.kcwcurstinf {font-family: 'Nunito', sans-serif; font-size: 18px;display: inline-block;margin: 0;}
.kcwcurday {margin: 0;}
.kcwcurst {margin: 0 10px 0 5px;}
/*Using the css below you can make your style responsive!*/
#media (max-width: 600px){
.kcwcstyle {font-size: 14px;}
.kcwcurstinf {font-size: 12px;}
}
<div class="kcwsource"><p>This Pen was originally developed for KOCOWAFA.com</p></div>
<div class="CurTbx"><p class="kcwcurst kcwcstyle" id="kcwcurday"></p><p class="kcwcurst kcwcstyle" id="kcwcurtime"></p><p class="kcwcurstinf">(Seoul, Korea)</p></div>
Do it as easy:
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log(timeZone);
var d = new Date();
console.log(d.toLocaleString('en-US', { timeZone }));
I don't know an easy method to convert a date object to any time zone, but if you want to convert it to the local time zone, you can just convert it with Date.prototype.getTime() to the corresponding number of milliseconds, and back again.
let date0 = new Date('2016-05-24T13:07:20');
let date1 = new Date(date0.getTime());
console.log(`${date0}\n${date1}`);
For example, date.getHours() will now return 15 instead of 13 if you are, like me, in Austria (and it's summer).
I've read that the various datetime functions may exhibit non-standard behaviour in some browsers, so test this first. I can confirm that it works in Chrome.
People familiar with the java 8 java.time package, or joda-time will probably love the new kid on the block: the js-joda library.
Install
npm install js-joda js-joda-timezone --save
Example
<script src="node_modules/js-joda/dist/js-joda.js"></script>
<script src="node_modules/js-joda-timezone/dist/js-joda-timezone.js"></script>
<script>
var dateStr = '2012/04/10 10:10:30 +0000';
JSJoda.use(JSJodaTimezone);
var j = JSJoda;
// https://js-joda.github.io/js-joda/esdoc/class/src/format/DateTimeFormatter.js~DateTimeFormatter.html#static-method-of-pattern
var zonedDateTime = j.ZonedDateTime.parse(dateStr, j.DateTimeFormatter.ofPattern('yyyy/MM/dd HH:mm:ss xx'));
var adjustedZonedDateTime = zonedDateTime.withZoneSameInstant(j.ZoneId.of('America/New_York'));
console.log(zonedDateTime.toString(), '=>', adjustedZonedDateTime.toString());
// 2012-04-10T10:10:30Z => 2012-04-10T06:10:30-04:00[America/New_York]
</script>
In true java nature, it's pretty verbose lol. But, being a ported java library, especially considering they ported 1800'ish test cases, it also probably works superbly accurately.
Chrono manipulation is hard. That's why many other libraries are buggy in edge cases. Moment.js seems to get timezones right, but the other js libs I've seen, including timezone-js, don't seem trustworthy.
I was having trouble using Moment Timezone. I am adding this answer just so if somebody else faces the same issue. So I have a date string 2018-06-14 13:51:00 coming from my API. I know that this is stored in UTC but the string doesn't speak for itself.
I let moment timezone know, what timezone this date is from by doing:
let uTCDatetime = momentTz.tz("2018-06-14 13:51:00", "UTC").format();
// If your datetime is from any other timezone then add that instead of "UTC"
// this actually makes the date as : 2018-06-14T13:51:00Z
Now I would like to convert it to a specific timezone by doing:
let dateInMyTimeZone = momentTz.tz(uTCDatetime, "Asia/Kolkata").format("YYYY-MM-DD HH:mm:ss");
// now this results into: 2018-06-14 19:21:00, which is the corresponding date in my timezone.
Just set your desire country timezone and You can easily show in html it update using SetInteval() function after every one minut. function formatAMPM() manage 12 hour format and AM/PM time display.
$(document).ready(function(){
var pakTime = new Date().toLocaleString("en-US", {timeZone: "Asia/Karachi"});
pakTime = new Date(pakTime);
var libyaTime = new Date().toLocaleString("en-US", {timeZone: "Africa/Tripoli"});
libyaTime = new Date(libyaTime);
document.getElementById("pak").innerHTML = "PAK "+formatAMPM(pakTime);
document.getElementById("ly").innerHTML = "LY " +formatAMPM(libyaTime);
setInterval(function(today) {
var pakTime = new Date().toLocaleString("en-US", {timeZone: "Asia/Karachi"});
pakTime = new Date(pakTime);
var libyaTime = new Date().toLocaleString("en-US", {timeZone: "Africa/Tripoli"});
libyaTime = new Date(libyaTime);
document.getElementById("pak").innerHTML = "PAK "+formatAMPM(pakTime);
document.getElementById("ly").innerHTML = "LY " +formatAMPM(libyaTime);
},10000);
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
});
there is server issue pick gmt+0000 standard time zone you can change it by using library moment-timezone in javascript
const moment = require("moment-timezone")
const dateNew = new Date()
const changeZone = moment(dateNew);
changeZone.tz("Asia/Karachi").format("ha z");
// here you can paste "your time zone string"
A bit redundant with all these answers, but this worked for me for getting the current Date object with a specific hourly offset.
function hourToMs(hour)
{
return hour * 60 * 1000 * 60;
}
function minToMs(min)
{
return min * 60 * 1000;
}
function getCurrentDateByOffset(offset)
{
// Get the current timezone in milliseconds to reset back to GMT aka +0
let timezoneOffset = minToMs((new Date()).getTimezoneOffset());
// get the desired offset in milliseconds, invert the value because javascript is dum
let desiredOffset = hourToMs(offset * -1);
return new Date(Date.now() + timezoneOffset - desiredOffset);
}
// -6 hours is central timezone
console.log("The time is: " + getCurrentDateByOffset(-6));
There is an npm module called timezones.json you can use for this. It basically consists of a json file with objects containing information on daylight savings and offset.
For asia/jakarta, it would be able to return this object:
{
"value": "SE Asia Standard Time",
"abbr": "SAST",
"offset": 7,
"isdst": false,
"text": "(UTC+07:00) Bangkok, Hanoi, Jakarta",
"utc": [
"Antarctica/Davis",
"Asia/Bangkok",
"Asia/Hovd",
"Asia/Jakarta",
"Asia/Phnom_Penh",
"Asia/Pontianak",
"Asia/Saigon",
"Asia/Vientiane",
"Etc/GMT-7",
"Indian/Christmas"
]
}
You can find it here:
https://github.com/dmfilipenko/timezones.json
https://www.npmjs.com/package/timezones.json
hope it's useful
This is worked for me in React Native Application.
import moment from 'moment-timezone'
function convertTZ(date, tzString) {
const formatedDate = moment(date).tz(tzString).format()
return formatedDate
}
export {convertTZ}
This should work for everyone. You can test out different time zones by changing the time manually on your machine. This function will adapt accordingly.
function getCurrentTime() {
const d = new Date() //2022-07-22T16:27:21.322Z
const t = d.getTime(); //d in milliseconds 1658507241322
const offset = -d.getTimezoneOffset()/60 //current offset in hours -4
const curretMilli = t + (offset * 3600000) //cuuret local time milliseconds need to convert offset to milliseconds
return new Date(curretMilli) //converts current local time in milliseconds to a Date //2022-07-22T12:27:21.322Z
}
This is UTC date; converting UTC to IST timezone;
let sampleArray = [
{
date: "2022-12-22T19:16:26.803"
},
{
date: "2022-12-22T19:16:26.77"
},
{
date: "2022-12-22T19:16:26.737"
},
{
date: "2022-12-22T19:16:26.72"
}
];
// Get all the results whose boolresult is 'true'
// solution 1
sampleArray.map((element) => {
let utcDate = new Date(element.date).getTime();
let dateIST = new Date(utcDate);
dateIST.setHours(dateIST.getHours() + 5);
dateIST.setMinutes(dateIST.getMinutes() + 30);
element.date = dateIST;
});
console.log("Result ==>>", sampleArray);
// solution 2
sampleArray.map((element) => {
element.date = new Date(element.date).toLocaleString("en-US", {
timeZone: "Asia/Kolkata"
});
});
console.log("Result 2==>>", sampleArray);
I am in GMT +2 timezone and Daylight saving time on.
My requirement is to ask user a date and convert it into UTC without DST consideration.
when I do console.log(new Date()),
it gives me "Wed Oct 26 2016 18:00:00 GMT+0300 (Turkey Daylight Time)"
I want to send server a UTC format date which server is going to save in Database.
var extractTime = new Date(timeof.edtime); //timeof.edtime contains date given by user.
var d = extractTime.getDate();
var m = extractTime.getMonth();
var y = extractTime.getFullYear();
var h = extractTime.getHours();
var mm = extractTime.getMinutes();
timeof.edtime = moment(new Date(y, m, d, h, mm)).utc().format("YYYY-MM-DD HH:mm");
After converting to utc, timeof.edtime is "2016-09-26 15:00" because it subtract 3 hours to go to GMT. (subtracted 2 hours of standard turkish time) (subtracted -1 of DST)
I want to subtract date to UTC by not considering DST and in our case my expectation is to get hour as "16:00" and not "15:00"
How to convert date to UTC without Daylight saving consideration.
any solution using moment js or jquery will be helpful.
I am testing on chrome.
by browsing through few link it says new Date() will give in standard time and doesn't consider DST consideration but this is not I observed and created plunk to reproduce new Date().toUTCString() consider DST as well, how to avoid subtraction of DST?
https://plnkr.co/edit/tjCOoJqXMHGzCD8B5LdL?p=preview
Inspired by this answer, you could make the time correction as follows:
function compensateDST(dt) {
var janOffset = new Date(dt.getFullYear(), 0, 1).getTimezoneOffset();
var julOffset = new Date(dt.getFullYear(), 6, 1).getTimezoneOffset();
var dstMinutes = dt.getTimezoneOffset() - Math.max(janOffset, julOffset);
dt = new Date(dt);
dt.setMinutes(dt.getMinutes() - dstMinutes);
return dt;
}
// Use your date here:
var extractTime = new Date('2016-10-26 18:00');
// Truncate to minute precision:
var extractTime = new Date(extractTime.getTime() - extractTime.getTime() % 60000)
console.log('Local time:', extractTime.toString());
console.log('UTC time before correction:', extractTime.toISOString());
// Compensate for the DST shift:
var extractTime = compensateDST(extractTime);
console.log('UTC time after correction:', extractTime.toISOString());
try this:
+180 is GMT+0300 (Turkey)
var x = new Date();
var newdate = new Date();
if((x.getTimezoneOffset()) != 180){
newdate = new Date(x.getTime() + (60000*(x.getTimezoneOffset()+180)));
}
console.log(newdate);
I tried many times to convert utc datetime to local datetime,and I have failed. My utc datetime format is
Fri Mar 8 23:12:27 UTC+0200 2013
Also my JavaScript code is
var time = Date(param_time);//param_time is /Date(1362866006646)/
And then time is being Sun Mar 10 00:21:54 UTC+0200 2013 I need to datetime as 2008-01-28T20:24:17Z because I will convert local datetime to pretty datetime.
http://ejohn.org/files/pretty.js
How can I do this ? I looked at many questions on stackoverflow but no one does it work. Thank you.
In order to format your Date correctly use toISOString():
var time = param_time.toISOString();
Note that param_time needs to be a valid Date object.
References
MDN: Date (sections: Syntax, Example: ISO 8601 formatted dates)
I rarely use javascript and all this date time conversion are mystery to me as well, javascript is a client side technology and all this "UTC" phrases means nothing (at least to me), as all the kind of getUTC...()/setUTC...() functions works in local time, the same is goes for all Date.to...String() functions, even the new Date() (that due to the docs) s'd be initialized in UTC, also give a local time.
However, if you have a (correct) date in UTC and wish to convert it to current (client side) local time, then you need getTimezoneOffset(), or shortly:
function UTCToLocalTime(d) {
var timeOffset = -((new Date()).getTimezoneOffset()/60);
d.setHours(d.getHours() + timeOffset);
return d;
}
var time = new Date(Date.parse('Fri Mar 8 23:12:27 UTC+0200 2013'));
alert(UTCToLocalTime(time)); // Sat Mar 9 01:12:27 UTC+0200 2013
//p.s. or...
function UTCToLocalTime2(d)
{
return new Date(d.toString().replace(/UTC.*/g,"") + d.getYear());
}
var timezone = "UTC+01:30";
var start = new Date();
if(timezone != "UTC"){
timezone = timezone.replace(/UTC/g,"");
znak = timezone.charAt(0);
timezone = timezone.replace(/[+|-]/g,"");
timezone = timezone.split(":");
//var start = new Date(start.toString() + " " + timezone);e.
//alert(start.toString());
if(znak == "+") start = new Date(start.getTime() + (timezone[0]*60*60000 + timezone[1] * 60000) );
if(znak == "-") start = new Date(start.getTime() - (timezone[0]*60*60000 + timezone[1] * 60000) );
}
var hours = start.getUTCHours();
var minutes = start.getUTCMinutes();
var seconds = start.getUTCSeconds();
var day = 10;
var month = 04;
var year = 2015;
var dateUtc = Date.UTC(year, month - 1, day + 1, 0, 0, 0);
> 1428710400000
var toDate = new Date(dateUtc);
> Fri Apr 10 2015 21:00:00 GMT-0300 (Hora oficial do Brasil)