get UTC date using moment in javascript - javascript

I am getting a utc date using utcDate = moment.utc(new Date()).format(). But this utcDate is a string, not Date object. By using new Date(utcDate),it is again converting utc date lo my local date. Please help me in getting utc date object.
I work in javascript.
utcDate = moment.utc(new Date()).toDate() is converting it to my local date Sun Sep 01 2019 05:30:00 GMT+0530 (India Standard Time)

Using moment.js
var date = moment();
console.log(date.format()) // 2019-08-30T11:08:27+05:30
date = moment().utc();
console.log(date.format()); // 2019-08-30T05:38:27Z
Using Javascript
var dateObject = new Date();
dateObject.toLocaleString()
"8/30/2019, 10:55:19 AM" // My current time
var utcDateObject = new Date( dateObject.getUTCFullYear(), dateObject.getUTCMonth(), dateObject.getUTCDate(), dateObject.getUTCHours(), dateObject.getUTCMinutes(), dateObject.getUTCSeconds() );
utcDateObject.toLocaleString()
"8/30/2019, 5:26:04 AM" // UTC time which is 5.5 hours less than my local time

Related

How to get last day of previous month using current date?

I'm trying to get the last of day of previous month using the current date:
var myDate = new Date();
According to MDN:
if 0 is provided for dayValue, the date will be set to the last day of the previous month.
But when set date to zero:
myDate.setDate(0)
console.log(JSON.stringify(myDate));
I get "2021-08-01T01:18:34.021Z" which first day of the current month. What is wrong with this approach?
JSON.stringify() is serializing the timestamp with a Z timezone, indicating UTC. The difference between UTC and your local timezone is causing the date to rollover to the next day.
You can use toLocaleString() to print the date in your local timezone:
var myDate = new Date();
myDate.setDate(0);
console.log(myDate.toLocaleString());
I would use dateInstance.toString() or dateInstance.toLocaleString():
const myDate = new Date;
myDate.setDate(0); myDate.setHours(0, 0, 0, 0);
console.log(myDate.toString()); console.log(myDate.toLocaleString());
You can use date-fns package
var df = require("date-fns")
let myDate = new Date() //Thu Aug 05 2021 22:16:09
let lastDayOfPrevMonth = df.endOfMonth(df.subMonths(myDate, 1)) //Sat Jul 31 2021 23:59:59 GMT-0400

Convert Javascript Date object to other timezone Date Object

How to convert Javascript Date Object to another timezone but the result must be Date object with the correct timezone
let date = new Date();
console.log(date);
date = date.toLocaleString('en-US', { timeZone: 'America/Vancouver' });
date = new Date(date);
console.log(date);
that gives the following result, the last result line (Date/Time) is correct but the time zone is incorrect which is still GMT-0500 (Colombia Standard Time) but must be GMT-0800 (Pacific Standard Time) timezone
Wed Jan 20 2021 00:14:11 GMT-0500 (Colombia Standard Time)
Tue Jan 19 2021 21:14:11 GMT-0500 (Colombia Standard Time)
You may try this :
let date = new Date();
console.log(date);
date = date.toLocaleString("en-CA", {
timeZone: "America/Vancouver",
timeZoneName: "long",
});
console.log(date);
Output:
Wed Jan 20 2021 09:18:16 GMT+0300 (Arabian Standard Time)
2021-01-19, 10:18:16 p.m. Pacific Standard Time
Once you get the correct TimeZone, you may change how the date and time are displayed by string manipulation if you need too.
Update:
This may not look pretty but i believe it should satisfy the requirements:
let date = new Date().toLocaleString("en-US", {
timeZone: "America/Vancouver",
timeZoneName: "short",
});
let date1 = new Date(date);
//adding a new property to Date object called tz and initializing it to null
Date.prototype.tz = null;
//stting the tz value to the Time zone output from toLocalString
date1.tz = date.slice(date.length - 3);
console.log(date1.toISOString() + " " + date1.tz);
console.log(date);
console.log(typeof date1);
Output:
2021-01-20T09:01:06.000Z PST
1/20/2021, 1:01:06 AM PST
Object
What i've done is create a new property of the object date to replace the built-in time zone property in Date, hence you get an object with a user specified Time zone.

Is there an external api to get the current date/time in British Summer Time format

I have the following javascript function, where i am getting 2 variables from our system (expireddate + modifieddate)+ i am getting the current Date, as follow:-
function(){
var expirydate = item.get_item('ExpireDate');
var modifieddate = item.get_item('Modified');
var currentdate = new Date();
now in my case all the variables will be in this format Tue Jun 11 2019 00:00:00 GMT+0100 (British Summer Time).. and i am not facing any issue since my pc is also using the (British Summer Time) date, so the var currentdate = new Date(); will be compatible with other formats... but my question is how i can guarantee that var currentdate = new Date(); will always be in the (British Summer Time) date regardless of the users' PCs settings? so if the user is using another date format, to have the var currentdate = new Date(); in (British Summer Time) date format ? can i for example get the current date from external source?
I think I understand what you are looking for, and if so, you will want to use toLocaleString(), and tell it what format you would like the result to be in.
The following will result in british time format in the UTC timezone.
let date = new Date()
console.log('UTC:', date.toLocaleString('en-GB', { timeZone: 'UTC' }))
console.log('Guernsey:', date.toLocaleString('en-GB', { timeZone: 'Europe/Guernsey' }))
console.log('Guernsey Time:', date.toLocaleTimeString('en-GB', { timeZone: 'Europe/Guernsey' }))

Converting a UTC date string to another timezone maintaining the same format

I'd like to convert a UTC date string into the current users timezone and maintain the format of the date string.
For example, I have this code which works:
var data = '2017-04-24 12:06:37';
var date = new Date(data+' UTC');
console.log(date.toString()); // logs "Mon Apr 24 2017 08:06:37 GMT-0400 (Eastern Daylight Time)"
How do I get this to output the new date string in the exact same format dynamically?
You have to add UTC to the string before you convert it to a date.
To convert any date to a UTC string, you can use
var UTCstring = (new Date()).toUTCString();
See my snippet. It compares the five different methods.
var date = new Date('2017-04-24 12:06:37 PM UTC');
var local = date.toString();
var utc = date.toUTCString();
var iso = date.toISOString();
var dateString = date.toDateString();
console.log(date);
console.log(local);
console.log(utc);
console.log(iso);
console.log(dateString);
Solution I used with momentjs:
moment.utc(value).local().format('YYYY-MM-DD HH:mm:ss');

Format date time JavaScript

How to format date and time like this in JavaScript ?
March 05, 2012 # 14:30 (UTC - 9:30)
I use this code to calculate EST time :
function getDate() {
var now = new Date();
var utc = now.getTime() + (now.getTimezoneOffset() * 60000);
return new Date(utc + (3600000 * -4));
}
I use the date-time-format that Tats recommended because doing it manually is a huge PIA.
var yourDate = dateFormat(getDate(), "mmmm dd, yyyy # HH:MM) + "(UTC -9:30)";
Keep in mind this isn't Daylight Savings aware.. and you are asking for UTC -9:30 in your format, but your function converts to -4. Also, I believe that now.getTime returns in UTC.. so you can just add your difference there.
JavaScript Date Format
Check out date.js! It's a really powerful little library for working with Dates in JavaScript.
To get today's date in EST, you can do something like...
var today = new Date();
today.toString(); // outputs "Wed Apr 11 2012 15:40:40 GMT-0500 (CDT)"
today.setTimezone("EST");
today.toString(); // outputs "Wed Apr 11 2012 14:40:40 GMT-0500 (CDT)"
Also, its worth mentioning to checkout moment.js. I think the two libraries complement each other.
If you do just
var now = new Date();
document.write(now);
you will get
Wed Mar 14 2012 20:53:06 GMT+0000 (GMT Standard Time)
Link1, Link2.
Is it what you want?

Categories