new Date(UTCstrings), convert an UTCStrings to other timezone (not local) - javascript

I know how to use new Date(UTCStrings) to local timezone.
But now, the question is how to convert an UTCString to other timezone (not local).
e.g.
The UTCString is '1338480000000'.
My local timezone is UTC+4.
I want to convert the date(UTCString) to UTC+9.
How can I do it?
Appreciate for your help!
Update
Thanks for BalaKrishnan's help.
I follow BalaKrishnan's key points maked a simple function. Hopefully, this will help others.
function utcToOtherTimezone(utcString, timezone){
var isoDt = new Date(utcString), // do this to convert it to iso time:
dt = isoDt.addMinutes( isoDt.getTimezoneOffset() + (timezone * 60) );
return dt.toLocaleDateString() + ' ' + dt.toLocaleTimeString();
}
$('#dtime').html(utcToOtherTimezone(1341282169000, +8));​
And don't forget to add datejs
Online testing example http://jsfiddle.net/ysjia/FWbZ8/. Enjoy it.

First create a Date object from the UTCString as follows:
var utcString = 1338480000000;
// This will however be in local time, not iso time.
var isoDt = new Date(utcString);
// do this to convert it to iso time:
isoDt.addMinutes( isoDt.getTimezoneOffset()
);
// addMinutes is an API from Date.js.
Now the isoDt object has it's date value the same as the UTC date, to which you can add the necessary offset +9 or whatever.
Refer to this jquery faq that discusses this:
http://jqfaq.com/how-to-parse-a-date-string-disregarding-time-zones/

Related

Add time to string data/time

I am trying to pass a time stamp to my API that comes in the format of YYYY-MM-DD HH:MM:SS but i need to manipulate the time to add 5 hours.
Have I done something wrong here? Do I need to convert it to a JavaScript date first?
var manDate = "2020-08-16 16:15:00"
manDate.setHours(manDate.getHours() + 5);
data.manDate = manDate
console.log(manDate)
Expected output - 2020-08-16 21:15:00
When you create a var for date, you need to add the 'new Date()' method.
var manDate = new Date("2020-08-16 16:15:00");
manDate.setHours(manDate.getHours() + 5);
console.log(manDate.getHours());
And to log the hours use getHour() again in the log statement.
Use simpleDateFormat to format the date, then cast the formatted date to calendar and add hours to it.
Try with below code.
SimpleDateFormat sdfObj = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdfObj.parse("2020-08-16 16:15:00");
Calendar calendar = sdfObj.getCalendar();
calendar.add(Calendar.HOUR_OF_DAY, 5);
The question was asked to give a solution in java earlier. Below is the answer as per java.
Date newDate = DateUtils.addHours(oldDate, 5);

Getting wrong date in Node.js

I tried all the solutions i found here but none work.
Im just trying:
var a = new Date();
console.log(a);
//2020-01-12T05:05:17.320Z
//Time in my timezone: 2020-01-12T02:05:17.320Z
I'm from Brazil, o the timezone is -3:00
I already installed moment.js and tryed:
var moment = require('moment-timezone');
moment().tz("America/Sao_Paulo").format();
var a = new Date();
console.log(a);
but i keep getting whithout my timezone. I also tryed setting the TZ without the moment.js and didn't work.
I cant use some solution that change the way to call the "new Date()" because I have to parse a string to an object that contains Date and I use Prompts module, that get a date from console, that already return a date. I don't know what to do more.
Thanks for any help.
*I'm running on Windows, and the time is right, the configuration is pointing to the right timezone
edit1: more info
The best way that I found was add 'getTimezoneOffset' (minutes) using moment.js
//Will returns the current "wrong" time in formart '2020-09-29T19:47:46.411Z'
//Expect: 2020-09-29T16:47:46.411Z
console.log(new Date())
So if you want see the full date in format ('DD-MM-YYYY HH:mm') of any object
var moment = require('moment')
// specificDay is a Date (type: Object) like '2020-09-22T00:00:00.000Z'
// previously retrieved from the database without information about the time('HH:mm')
// Only with 'YYYY-MM-DD'
moment(specificDay, "YYYY-MM-DD").add(new Date().getTimezoneOffset(),'minute').format('DD-MM-YYYY HH:mm')
You're very close. Moment is a Javascript library that makes formatting time very easy. You are creating your moment object, but you're not outputting it.
I made a very slight change (2nd line) and it works as expected:
var moment = require('moment-timezone');
console.log(moment().tz("America/Sao_Paulo").format());
If you want it formatted nicely, see this page: https://momentjs.com/.
For example:
console.log(moment().tz("America/Sao_Paulo").format('lll'));
// output: Jan 12, 2020 2:45 AM
How does it work?
moment() creates a time object (just like new Date(), but it's moment's special time object). .tz() is calling the timezone function and we give it your time zone as a string "America/Sao_Paulo". .format() then outputs it in a nice custom string. console.log() outputs the whole string to the screen.
Node takes UTC timestamp
https://www.google.com/search?client=firefox-b-d&q=current+utc+time+online
So you can convert to a locale string and after that create a new date. This is a example for mexico city
let mx = (new Date()).toLocaleString('se-SE',{ timeZone: 'America/Mexico_City'}) + "Z";
return new Date(mx);

moments JS - correct way to compare local time

I'm trying to use moment.js to compare a date stored in the database (which is set to Europe/London timezone) against the current users time, taking into account their timezone.
I get a date string returned from the database and want to use the fromNow() function, as follows:
console.log(dbDate);
console.log(moment().format());
console.log(moment(dbDate).fromNow());
// DB stored time (Europe/London)
// 2017-09-26 06:56:26
// Current user time (timezone is Pacific Time / Los Angeles)
// 2017-09-25T23:59:03-07:00
// String output by fromNow() function, which should reflect the timezone difference but doesn't
// in 7 hours
I want the fromNow() string to take account the timezone difference and this should always be a time "ago" as opposed to in the future.
I'm probably missing something quite obvious with the library, so apologies in advance if this is very simple.
// get the current time so we know which offset to take
var now = moment.utc();
// get the zone offsets for this time, in minutes
var NewYork_tz_offset = moment.tz.zone("America/New_York").offset(now);
var MY_DATE = moment(dbDate);
// calculate the difference in hours
console.log((NewYork_tz_offset - MY_DATE) / 60);
Does this help your cause?
You have to use moment timezone, you can parse dbDate specifying "Europe/London" timezone using moment.tz:
The moment.tz constructor takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier.
Then you can use moment diff and fromNow.
Here a live example:
var dbDate = "2017-09-26 06:56:26";
var now = moment();
var momDbDate = moment.tz(dbDate, "Europe/London");
var pacificTime = moment("2017-09-25T23:59:03-07:00");
console.log(dbDate);
console.log(moment().format());
console.log(momDbDate.fromNow());
console.log(momDbDate.diff(now, 'hours'));
console.log(momDbDate.diff(pacificTime, 'hours'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data-2012-2022.min.js"></script>

parsing a UTC ISO date to a local time date in javascript/jquery

I have tried to search for the answer already, and although I find answers that are very similar, I don't think they are exactly what I am looking for. Please forgive me if this is already answered elsewhere.
I am trying to parse an ISO date in javascript so that I can compare it to the client system date and display information depending on if the ISO date is before or after the client system date.
This was fine until I needed to support IE8 and now I am stuck.
I have created a function because I have three different dates that I need to do this to.
for example, my ISO date is: 2015-12-22T11:59 in UTC time.
but once my date is parsed, the full date is 11:59 in local time, no matter which time zone i test, it's always 11.59 in THAT time zone.
I know that the function I have created currently doesn't do anything with timezone, this is where I am stuck. I don't know what to add to get my end date to change as a reflection of the timezone of the clients machine.
any help or advice would be greatly appreciated.
I am not able to use something like moments.js because I have an upload restriction.
Jquery is available though. or plain javascript.
<script>
function setSaleContent() {
//creating a new date object that takes the clients current system time. so we can compare it to the dates stored in our array
var currentDate = new Date();
console.log(currentDate + " this is the clients date ");
//These variables actually come from an external array object, but I'm putting them in here like this for this example.
var destinations = {
freedate: "2015-12-16T11:59",
courierdate: "2015-12-22T11:59",
nextdaydate: "2015-12-23T11:59",
}
//fetch all the ISO dates from the array.
var freeDateISO = destinations["freedate"];
var courierDateISO = destinations["courierdate"];
var nextdayDateISO = destinations["nextdaydate"];
//I am creating this reusable function to split up my ISO date for the sake of IE8.. and create it into a date format that can be compared against another date. I know that this isn't doing anything with my timezone and that is where my problem lies.
function parseDate(str) {
var parts = /^(\d{4}).(\d{2}).(\d{2}).(\d{2}):(\d{2})/.exec(str);
if (parts) {
return new Date(parts[1], parts[2] - 1, parts[3], parts[4], parts[5]);
}
return new Date();
}
//I would like this date to change to reflect the time zone of the clients system time.
//currently returns the date at 11.59 regardless of timezone.
//If i was in GMT i would want it to say 11.59
//If i was in CT time I would like this to say 05.59
//If i was in Perth I would like this to say 19:59
var freeDate = parseDate(freeDateISO);
console.log(freeDate + " this is the converted date for IE")
}
window.onload = setSaleContent;
The simple solution is to append Z to the ISO date to indicate it is in UTC time, such as 2015-12-22T11:59Z.
When JavaScript parses that date as a string, it will then automatically convert the UTC date to the local time zone.
While this is simple enough with a parsing call in the form new Date(str);, it will not play nice with your parse call with numerical arguments targeting IE8 and other old browsers.
A polyfill for parsing ISO dates with timezone exists: Javascript JSON Date parse in IE7/IE8 returns NaN
This can replace your custom parseDate function after some modification to take an input string.
Alternatively, implement your own custom date manipulater to account for the local timezone using the .getTimezoneOffset() method on the newly created date, which gives the time zone offset in minutes, but you will have to come up with a method of utilising the offset such as adjusting hours and minutes, due to the limited methods of the JavaScript date object.

How to Convert date string to json date format in javascript?

In my application I am getting date in a string format like :
var date="1988-11-4".
I am calling back the WCF service and sending data to the service as Json format. But my problem is the WCF service is only accepting the dates as {DoB:"/Date(570931200000+0530)/"} format.
can you please tell how do I convert date to json date format like:
var jasonDate="/Date(570931200000+0530)/". Where 570931200000 is the miliseconds calculated since from "1970-01-01" and +0530 is the Timezone.
As a best guess, and to give you something to work with, until you understand what the relationship is and come back and explain things better along with what you have tried and the precise nature of the problem with your code.
var dateTime = '1988-05-03',
parts = dateTime.split('-'),
date;
parts[1] -= 1;
date = new Date(Date.UTC.apply(null, parts));
document.body.textContent = '/Date(' + date.getTime() + '-0000)/';
This might work:
var jsonDate = new Date(date).toJSON();
As the initial variable is only a string it would not be recognised as a date so create a date from it then convert that to JSON.
Thank you all for your response. I have got solution to my query. Here in the string "/Date(1208559600000-0700)/" 1208559600000 is the milliseconds calculated since from Jan 01 1970 and -700 is the time zone.
This the code that worked for me:
convertToJsonDate: function (date) {
var diff = date.getTime();
var jsonDate = "\/Date(" + diff + "-0700)\/";
return jsonDate;
},

Categories