JS:前端把当地时间转换为UTC时间写法

1.主要方法是用到:toUTCString()这个方法

 

具体的例子如下,这边应用到datepicker

<input type="text" class="form-text datepicker" id="startDate">

  

 var startDate = $("#startDate").datepicker("getDate");
            var startDateUTC = startDate.toUTCString();
            console.log("DatePicker获取startDate:" + startDate);
            console.log("DatePicker获取startDate转成UTC:" + startDateUTC);
            var startDateVal = $("#startDate").val();
            console.log("DatePicker获取字符串值 .val()" + startDateVal);
            var localDate = new Date(startDateVal);
            console.log("DatePicker .val() 字符串格式转成时间格式:" + localDate);
            var newDateString = localDate.getFullYear() + "/" + (localDate.getMonth() + 1) + "/" + localDate.getDate();
            console.log("上面的时间格式转换成简单的时间格式:" + newDateString);
            newDateString = newDateString + " 23:59:59";//转换成自己想要的时间
            var newLocalDate = new Date(newDateString);
            var utcDate = newLocalDate.toUTCString();
            console.log("new local date:" + newLocalDate);
            console.log("utc date:" + utcDate);

测试结果如下:

 

 

 

posted @ 2022-05-05 14:37  katesharing  阅读(2711)  评论(0编辑  收藏  举报