如何使用Moment解析时间字符串而不偏移?

时间:2019-10-05 16:21:18

标签: javascript momentjs moment-timezone

我有一个特殊的用例,其中应用程序总是必须使用America/Chicago时区中的时间。因此,我将Moment的默认时区设置为moment.tz.setDefault("America/Chicago");

通过此设置,我以js格式America/ChicagoMM/DD/YYYY h:mm A时区中将所有来自客户端的日期时间输入发送到服务器。而且,只要客户端请求时间字段,服务器就会以相同的格式返回America/Chicago时区的时间。

现在有一种情况,我必须解析服务器返回的日期时间值,并将其与当前America/Chicago时间进行比较。我尝试过了

moment.tz.setDefault("America/Chicago");

let now = moment();

// serverResponse is America/Chicago datetime string in format MM/DD/YYYY h:mm A

let serverResponseMoment = moment(serverResponse);

// The above statement is where I am facing issue. Since the users could be from
// anywhere, moment(serverResponse) will be assuming the serverResponse string to
// be of the local timezone as there is no offset part attached to the string.

return now.isBefore(serverResponseMoment);

也尝试过

let serverResponseMoment = moment.tz(serverResponse,"America/Chicago");

// The above statement assumes the serverResponse to be in UTC and give me an "America/Chicago"
// date-time after conversion

我也尝试过moment.utc(serverResponse)。当执行最后一个条件检查时,所有解析都会失败。

我想要的是一个时刻实例,在已经设置的默认时区中,将我的serverResponse保留为基础DateTime。

或执行此操作的某些语句

Hey Moment, serverResponse is already in "America/Chicago" timezone, you don't have to make any sort of timezone assumptions. Just parse it and return an instance of yourself

有什么想法吗?

谢谢

1 个答案:

答案 0 :(得分:2)

如果您已经知道时区和字符串格式,则可以创建自己的serverResponse解析器:

const momentParserFactory = (format, tz) => (str) => moment.tz(str, format, tz);
const chicagoMoment = momentParserFactory('MM/DD/YYYY h:mm A', 'America/Chicago');

let now = moment();
let serverResponse_1 = '10/07/2019 11:40 AM';
let serverResponseMoment_1 = chicagoMoment(serverResponse_1);

console.log(`"Now" is: ${now.format()}`)
console.log(`Server response date 1: ${serverResponseMoment_1.format()}`);
console.log(`"Now" is before server response date 1: ${now.isBefore(serverResponseMoment_1)}`);

let serverResponse_2 = '10/09/2020 4:20 AM';
let serverResponseMoment_2 = chicagoMoment(serverResponse_2);

console.log(`Server response date 2: ${serverResponseMoment_2.format()}`);
console.log(`"Now" is before server response date 2: ${now.isBefore(serverResponseMoment_2)}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.26/moment-timezone-with-data.min.js"></script>