问题
I have a string like 07-Oct-2019 11:02
in BST format .I have to convert into UTC time in same format which will be 07-Oct-2019 10:02
.
I have tried many ways and tried to find some inbuilt function but nothing worked . I tried to write a function which will split string and then convert it into date and then UTC but that also did not work .
This is what i have tried
var fullDate = "07-Oct-2019 11:02";
fullDate = fullDate.split(' ');
var date = fullDate[0].split("-");
var time = fullDate[1];
var newDate = date[0] + '-' + date[1] + '-' + date[2] + ' ' + time;
var k = new Date(newDate);
alert(d);
But this result into current date into IST .
Please help how i can do this .
I am using DOJO framework .
回答1:
Use moment-timezone to do advanced operations with date and timezone.
Solution:
let date = "07-Oct-2019 11:02"
console.log(
moment.tz(date, "DD-MMM-YYYY HH:mm", "Europe/London").utc().format("DD-MMM-YYYY HH:mm")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.16/moment-timezone-with-data.min.js"></script>
回答2:
var date = "07-Oct-2019 11:02";
var a = date.split("-");
var b = a[2].split(" ");
var dateFormat = a[0] + ' - ' + a[1] + ' - ' + b[0] + ' ' + b[1];
var convertedDate = new Date(dateFormat);
weekdayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var dateString = convertedDate.getDate() + "-" + monthNames[convertedDate.getMonth()] + "-" + convertedDate.getFullYear() +" "+ convertedDate.getHours() + ":" + ("00" + convertedDate.getMinutes()).slice(-2);
console.log(dateString);
来源:https://stackoverflow.com/questions/58282149/not-able-to-convert-string-bst-date-format-to-utc-in-javascript