-1

I am trying to convert the date object to local time that is formatted by 'YYYYMMDDHHmmss'.

What I wanna do is like following.

var currentDate = new Date();
var timezone = "Asia/Tokyo";
var currentDateJst = moment(currentDate).tz(timezone).format('YYYYMMDDHHmmss');

I would like to know how to convert without moment-timezone library.

yagu
  • 127
  • 1
  • 9
  • 2
    Have you looked at the [documentation for the Date object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) at all? It has some useful methods, like `getDate`, `getMonth`, `getFullYear`, `getHours`, `getMinutes` and `getSeconds` – Jaromanda X Feb 01 '18 at 02:35
  • Does this help you? https://stackoverflow.com/questions/8083410/how-can-i-set-the-default-timezone-in-node-js – tremby Feb 01 '18 at 02:38
  • Like Tom scott said in [his video](https://www.youtube.com/watch?v=-5wpm-gesOY). You should use a librairy – Nicolas Feb 01 '18 at 02:42
  • `console.log(date.getFullYear()+''+date.getMonth()+''+date.getDate()+''+date.getHours()+''+date.getMinutes());` Thank you for the advice. I have confused to combine formatted and changing time zone. – yagu Feb 01 '18 at 02:46

2 Answers2

0

If you don't wanna use a library then there's no quick / easy way about. One way is just to add the difference from UTC.

For example tokoy is UTC+9. So now you can do:

const yourTime = new Date();    
console.log('your date is: ' + yourTime);

const minutesFromUTC = yourTime.getTimezoneOffset();    
const utcTime = new Date(yourTime.setMinutes(yourTime.getMinutes()+minutesFromUTC));
console.log('utc date is: ' + utcTime);

const tokyoFromUTC = 9*60; // Tokya is 9 hours    
const tokyoTime = new Date(utcTime.setMinutes(utcTime.getMinutes()+tokyoFromUTC));
console.log('tokyo date is: ' + tokyoTime);

https://jsfiddle.net/fz79mdg2/

Bergur
  • 2,668
  • 8
  • 15
0

You can use the ECMAScript Internationalization API if you want to format according to date-time format of a specific timezone. For example:

new Intl.DateTimeFormat(
    'ja-JP',
    {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        year: 'numeric', // 2018
        month: '2-digit',
        day: '2-digit',
        timezone: 'Asia/Tokyo' // Format in the order how it's used in Asia/Tokyo
    }
).format(new Date()).replace(/\D/g, '')

At the end, I just removed the non-numeric chars to display in the way you asked.

There is good documentation in MDN regarding Intl.DateTimeFormat