Convert UTC time to local time in nodejs while creating csv

22 Views Asked by At

When I convert utc time to local time its working in my local machine but when i deployed it on server then getting me UTC time only means it does not convert time into local. I have tried with moment library : 1.createdAt:moment(item.createdAt).local().format('DD/MM/YYYY hh:mm:ss A'), 2. createdAt:moment.utc(item.createdAt).local().format('DD/MM/YYYY hh:mm:ss A'),

const json2csvParser = new Parser({ fields, transforms: [ (item) => { return { ...item, createdAt:moment(item.createdAt).local().format('DD/MM/YYYY hh:mm:ss A'), 'country':item.location.country_name, service:item.service, activity:item.activity, email:item.email, }; } ] }); ... Please help me out.Thanks

1.createdAt:moment(item.createdAt).local().format('DD/MM/YYYY hh:mm:ss A'), 11/03/2024 01:26:00 PM -> utc 2. createdAt:moment.utc(item.createdAt).local().format('DD/MM/YYYY hh:mm:ss A'),

const json2csvParser = new Parser({ fields, transforms: [ (item) => { return { ...item, createdAt:moment(item.createdAt).local().format('DD/MM/YYYY hh:mm:ss A'), 'country':item.location.country_name, service:item.service, activity:item.activity, email:item.email, }; } ] }); input : 2024-03-11T13:26:00.119+00:00 expected output : 11/03/2024 06:56:00 PM actual output : 11/03/2024 01:26:00 PM

1

There are 1 best solutions below

0
hjuste On

You can explicitly set the timezone when converting UTC time to local time.

Here's how you can modify your code using the moment-timezone library:

const moment = require('moment-timezone');
const { Parser } = require('json2csv');

// Set the desired timezone
const timezone = 'Your/Timezone'; // For example, 'America/New_York'

const json2csvParser = new Parser({
    fields,
    transforms: [
        (item) => {
            return {
                ...item,
                createdAt: moment(item.createdAt).tz(timezone).format('DD/MM/YYYY hh:mm:ss A'),
                'country': item.location.country_name,
                service: item.service,
                activity: item.activity,
                email: item.email,
            };
        }
    ]
});

Replace Your/Timezone with the actual timezone relevant to your server's location. This ensures that the conversion is always done based on the specified timezone, regardless of the server's settings.

Make sure to install moment-timezone package if you haven't already:

npm install moment-timezone