angularmomentjs

Setting moment value to specific time zone directly


We are using Moment v2.30.1. We are attempting to apply a StartDateTime to an object but it is always being set to utc(). We want to set it directly to the America/Chicago time zone.

Here is the object with the startDateTime value:

export interface ExPCReq extends BaseModel {
    description: string | null | undefined;
    action: PA;
    startDateTime?: moment.Moment;
    userId: number;
}

This is how it currently is being set:

const pCReq: ExPCReq = {
            description: this.paFrmGrp.get('descriptionCtrl')?.value as string,
            action: PA.Move,
            startDateTime: moment.utc(),
            userId: this.userService.userDetails.value.userId
        };

I've tried a lot of things but this sets it to a null value because it says that it is an invald date because it's trying to set the value as a string, correct?

const pCReq: ExPCReq = {
            description: this.paFrmGrp.get('descriptionCtrl')?.value as string,
            action: PA.Move,
            startDateTime: moment.tz(moment.toString(), "MM/DD/YYYY h:mm a", "America/Chicago"),
            userId: this.userService.userDetails.value.userId
        };

When I inspect the startDateTime value, isUTC is always set to true, even in the second case above.

I'm just a little confused with this Moment library. It used to be a lot simpler as I used it about 10-12 yrs ago.

EDIT:
I've now tried this. When inspecting the startDateTime value after it is set, it is showing Thu Oct 24 2024 05:34:53 GMT-0500 (Central Daylight Time) and isUTC is still true but the value is still getting sent to my service as UTC time.

const pCReq: ExPCReq = {
            description: this.paFrmGrp.get('descriptionCtrl')?.value as string,
            action: PA.Move,
            startDateTime: moment.utc().tz("America/Chicago"),
            userId: this.userService.userDetails.value.userId
        };

Even when I set the value like this it stillgets sent to my service with UTC and isUTC is always true:

startDateTime: moment.tz("America/Chicago")

Solution

  • The answer lies here:

     startDateTime: moment().utcOffset(0, true),
    

    This sets the time to local, and on our servers, it's Central Time Zone. This does the job we need. Thanks for your time and comments.