0

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

通过此设置,我将所有日期时间输入从客户端以America/Chicagojs 格式发送到时区的服务器MM/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

有任何想法吗?

谢谢

4

1 回答 1

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>

于 2019-10-07T17:07:40.970 回答