I am using the following code in my angular app to display Date Time with Time Zone. it displays, July 22, 2022 12:36:52 GMT-4 I want to replace GMT-4 with specific time zone dynamically say , EDT or PST or CST
I am using the following code,
@Component({
selector: '',
styleUrls: [''],
templateUrl: '',
providers: [DatePipe]
})
public class Test {
clock;
constructor() {
this.clock = this.datePipe.transform(new Date(), 'MMMM d, y h:mm:s z');
}
}
CodePudding user response:
You can make use of pipes/custom pipes like this way:
script.js:
var toUTCDate = function(date){
var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
return _utc;
};
var millisToUTCDate = function(millis){
return toUTCDate(new Date(millis));
};
var tzOffsetMillis = function(){
var date = new Date();
var offsetMinutes = date.getTimezoneOffset();
var offsetMillis = offsetMinutes * 60000;
}
$scope.toUTCDate = toUTCDate;
$scope.millisToUTCDate = millisToUTCDate;
$scope.tzOffsetMillis = tzOffsetMillis;
index.html:
<body>
<div ng-controller="ctrl">
<div>
utc: {{millisToUTCDate(1400167800 * 1000) | date:'dd-M-yyyy H:mm Z'}}
</div>
<div>
local: {{(1400167800 * 1000) | date:'dd-M-yyyy H:mm Z'}}
</div>
<div>
alt UTC: {{(1400167800 * 1000 tzOffsetMillis()) | date:'dd-M-yyyy H:mm Z'}}
</div>
</div>
</body>
Refer: https://plnkr.co/edit/eLwnLZReCy8HXtJyO84q?p=preview&preview
CodePudding user response:
const timeZoneAbbreviated = () => {
const { 1: tz } = new Date().toString().match(/\((. )\)/);
// In Chrome browser, new Date().toString() is
// "Thu Aug 06 2020 16:21:38 GMT 0530 (India Standard Time)"
// In Safari browser, new Date().toString() is
// "Thu Aug 06 2020 16:24:03 GMT 0530 (IST)"
if (tz.includes(" ")) {
return tz
.split(" ")
.map(([first]) => first)
.join("");
} else {
return tz;
}
};
console.log("Time Zone:", timeZoneAbbreviated());
// IST
// PDT
// CEST