Pramod SR
Pramod SR

Reputation: 83

Convert the time stamp UTC to IST using JavaScript

I'm looking for a suitable way to convert a timestamp from UTC to IST using JavaScript DateTimeStamp "20160108120040".

The timestamp comes from an XML in my body request.

Upvotes: 8

Views: 40211

Answers (4)

Himanshu Tanwar
Himanshu Tanwar

Reputation: 336

Based on the accepted answer

export default class DateIST extends Date {
    constructor(params) {
        super(params)
        console.log(this)
        console.log(this.toString())
        console.log(this.toLocaleString())
        console.log(this.toISOString())
    }

    toISOString() {
        var date = new Date(this)
        date.setHours(date.getHours() + 5)
        date.setMinutes(date.getMinutes() + 30)
        return date.toISOString();
    }
}

var dateIST = DateIST('...')
console.log(dateIST.toISOString())

// For comparision purposes with Date, like when used in Mongoose Schema with ISODate in MongoDB
dbCollectionModel.find({ dateMongoDB: { $lt: dateIST.toISOString() } })

Upvotes: 0

GorvGoyl
GorvGoyl

Reputation: 49460

use toLocaleString and provide desired timezone:

new Date("yourInputDateInASuitableFormat").toLocaleString("en-US", {timeZone: 'Asia/Kolkata'})

Upvotes: 7

Prav
Prav

Reputation: 610

const getISTTime = () => {
  let d = new Date()
  return d.getTime() + ( 5.5 * 60 * 60 * 1000 )
}

Upvotes: 4

Matteo Baldi
Matteo Baldi

Reputation: 5828

First thing, take a look at JavaScript date formats and convert your input date accordingly, then you shoud take a look to the methods available in JavaScript for date manipulation (no external library required). It's pretty easy to do something like this:

var dateUTC = new Date("yourInputDateInASuitableFormat");
var dateUTC = dateUTC.getTime() 
var dateIST = new Date(dateUTC);
//date shifting for IST timezone (+5 hours and 30 minutes)
dateIST.setHours(dateIST.getHours() + 5); 
dateIST.setMinutes(dateIST.getMinutes() + 30);

Upvotes: 12

Related Questions