how to convert date into utc milliseconds with timezone in javascript - javascript

getTime() Is it return local or UTC milliseconds?
var startDate = new Date();
var val = (startDate.getTime()).toString();
Below logic will return UTC millisecords:
var startDate = new Date();
var val = (new Date(Date.UTC(
startDate.getFullYear(),
startDate.getMonth(),
startDate.getDate(),
startDate.getHours(),
startDate.getMinutes(),
startDate.getSeconds()
))).getTime().toString();
Need script for converting the date to UTC milliseconds with timezone like America/Los_Angeles

Here you create a new date:
var startDate = new Date();
This is set to your browsers current timezone, here mine is Turkey:
Fri Sep 02 2016 17:50:06 GMT+0300 (Turkish Summer Time)
If you convert this string Fri Sep 02 2016 17:50:06 GMT+0300 into millis then you will have the value with the GMT+0300:
Date.parse("Fri Sep 02 2016 17:50:06 GMT+0300")
>> 1472827806000
Here, you can create your date object with a different timezone and get the millis of it, let's say it is America/Los_Angeles:
1) Create date object
var d = new Date();
2) Get the local time value
var localTime = d.getTime();
3) Get the local offset
var localOffset = d.getTimezoneOffset() * 60000;
4) Obtain UTC
var utc = localTime + localOffset;
5) Obtain the destination's offset, for America/Loas_Angeles it is UTC -7
var offset = -7;
var ala = utc + (3600000*offset);
6) Now ala contains the milis value of America/Los_Angeles. Finally convert it to a new date object if needed:
var nd = new Date(ala);
Final: Now you can get the miliseconds of the new date object:
nd.getTime();
//or
ala;

Related

Adding 30 days to the converted date is giving me Invalid Date message in browser's console log

I have converted the timestamp 4/1/2021 00:00 into the format Thu Apr 01 2021 00:00:00 GMT-0500 (Central Daylight Time) as shown in the code below. However, adding 30 days is not giving me appropriate result.
//Handling Date String: 4/1/2021 00:00
function setStart(input) {
if (!(input instanceof Date))
console.log('Handling Date String:' +input)
input = new Date(Date.parse(input));
input.setHours(0);
input.setMinutes(0);
input.setSeconds(0);
input.setMilliseconds(0);
start = input;
return start;
}
var initialDate = setStart('4/1/2021 00:00');
console.log("Printing converted date below:");
console.log(setStart('4/1/2021 00:00'));
var date = new Date(); // Now
//date.setDate(date.getDate() + 30); // Set now + 30 days as the new date
date.setDate(initialDate + 30);
console.log("Printing date after adding 30 days below")
console.log(date);
/* var getDaysArray = function(start, end) {
for(var arr=[],dt=new Date(start); dt<=new Date(end); dt.setDate(dt.getDate()+1)){
arr.push(new Date(dt));
}
return arr;
};
var daylist = getDaysArray(new Date("2018-05-01"),new Date("2018-06-01"));
console.log(daylist); */
The browser's console is printing it like the following:
Handling Date String:4/1/2021 00:00
Printing converted date below:
Handling Date String:4/1/2021 00:00
Thu Apr 01 2021 00:00:00 GMT-0500 (Central Daylight Time)
Printing date after adding 30 days below
Invalid Date
What is causing it to print Invalid Date ?
You want to get the date after 30 days from the initialDate, don't you?
refer this
var date = new Date(initialDate); // Now
//date.setDate(date.getDate() + 30); // Set now + 30 days as the new date
date.setDate(date.getDate() + 30);
console.log("Printing date after adding 30 days below")
console.log(date);
You should something like
var date = new Date().getTime(); // Now
const offset = 30*23*3600*1000;
const newDate = new Date(date+offset).toLocaleString('en-US', {timeZone: 'CST'}); // Change added
console.log("Printing date after adding 30 days below")
console.log(newDate);

Create random UNIX timestamp based on if-else clause

How do I create a random UNIX timestamp using JavaScript:
Between now and the end of the working day (i.e. today between 08:00-17:00) if appointment.status === "today".
From tomorrow + 1 week but keeping in mind the working day (so it can be next week Tuesday 13:00, keeping in mind the working day i.e. 08:00-17:00) if appointment.status === "pending".
This is what I have done so far:
if(appointment.status === "today") {
appointment.timestamp = (function() {
return a
})();
} else if(appointment.status === "pending") {
appointment.timestamp = (function() {
return a
})();
}
This is similar to another question (Generate random date between two dates and times in Javascript) but to handle the "pending" appointments you'll also need a way to get a day between tomorrow and a week from tomorrow.
This function will return a random timestamp between 8:00 and 17:00 on the date that is passed to it:
var randomTimeInWorkday = function(date) {
var begin = date;
var end = new Date(begin.getTime());
begin.setHours(8,0,0,0);
end.setHours(17,0,0,0);
return Math.random() * (end.getTime() - begin.getTime()) + begin.getTime();
}
To get a random timestamp today between 08:00 and 17:00 today you could do:
var today = new Date();
var timestamp = randomTimeInWorkday(today);
console.log(timestamp); // 1457033914204.1597
console.log(new Date(timestamp)); // Thu Mar 03 2016 14:38:34 GMT-0500 (EST)
This function will return a random date between tomorrow and a week from tomorrow for the date that is passed to it:
var randomDayStartingTomorrow = function(date) {
var begin = new Date(date.getTime() + 24 * 60 * 60 * 1000);
var end = new Date(begin.getTime());
end.setDate(end.getDate() + 7);
return new Date(Math.random() * (end.getTime() - begin.getTime()) + begin.getTime());
}
To get a random timestamp between 08:00 and 17:00 on a random day between tomorrow and a week from tomorrow, you could do:
var today = new Date();
var randomDay = randomDayStartingTomorrow(today);
var timestamp = randomTimeInWorkday(randomDay);
console.log(timestamp); // 1457194668335.3162
console.log(new Date(timestamp)); // Sat Mar 05 2016 11:17:48 GMT-0500 (EST)

javascript getTime() returns greater value for older date compared to new date

javascript getTime() returns the number of milliseconds form midnight Jan 1, 1970 and the time value in the Date Object. but,
new Date('Wed Sep 16 2105 05:30:00 GMT+0530').getTime()
// returns 4282502400000
new Date('Tue Oct 26 2015 05:30:00 GMT+0530').getTime()
// returns 1445817600000
Shouldn't the value retuned by the later (Tue Oct 26 2015 05:30:00 GMT+0530) be greater.
I want to find the list dates between a given date (inform of timestamp) and today. I wrote the code below with the assumption that the value returned by getTime() for older dates will always be lesser than newer dates.
var timestamp = new Date('9/15/2105, 12:00:00 AM').getTime();
var startDate = new Date(timestamp);
// Date.UTC() to avoid timezone and daylight saving
var date = new Date(Date.UTC(startDate.getFullYear(),
startDate.getMonth(),
startDate.getDate()
));
var currentDay = new Date();
var currentDayTimestamp = new Date(Date.UTC(currentDay.getFullYear(),
currentDay.getMonth(),
currentDay.getDate()
)).getTime();
// day in millisec, 24*60*60*1000 = 86400000
date = new Date(date.getTime() + 86400000);
var dates = [];
console.info(date + ' : ' + date.getTime());
console.info(new Date(currentDayTimestamp) + ' : ' + currentDayTimestamp);
while(date.getTime() <= currentDayTimestamp) {
var dateObj = {
date: date.getUTCDate(),
month: date.getUTCMonth() + 1,
year: date.getUTCFullYear()
}
dates.push(dateObj);
date = new Date(date.getTime() + 86400000);
}
console.info(JSON.stringify(dates));
OUTPUT:
Wed Sep 16 2105 05:30:00 GMT+0530 (IST) : 4282502400000
Tue Oct 27 2015 05:30:00 GMT+0530 (IST) : 1445904000000
[]
The problem is a typo in your dates. One has the year 2105 which is much larger than 2015.

Javascript - Format date to yyyy-mm-dd from unixtime

I need some help with converting unixtime to a specific format. Here is what I am currently working with:
var date = "2014-05-01";
var indexPie = Date.parse(date);
I need indexPie in yyyy-mm-dd format. What I do not understand is that when log
var newDate = new Date(indexPie);
The results is:
Wed Apr 30 2014 18:00:00 GMT-0600 (Mountain Daylight Time)
when it should be:
Thur May 01 2014 18:00:00 GMT-0600 (Mountain Daylight Time)
Why is new Date(indexPie) resulting in Apr 30 and how do I get my correct format of yyyy-mm-dd?
Any suggestions would be great. Thanks.
I resolved the issue with the following:
var date = new Date(indexPie);
var year = date.getUTCFullYear();
var month = date.getUTCMonth() + 1;
var day = date.getUTCDate();
var dateString = year + "-" + month + "-" + day;
You are expecting that the value in date variable: "2014-05-01" will be parsed as in local timezone, but actually it is parsed as in UTC.
You can convert the date from UTC to local timezone like this:
var newDate = new Date(indexPie + new Date().getTimezoneOffset() * 60000);

Getting current time from the date object

function formatDate (input) {
var datePart = input.match(/\d+/g),
year = datePart[0].substring(2), // get only two digits
month = datePart[1], day = datePart[2];
document.write(new Date(day+'/'+month+'/'+year));
}
formatDate ('2010/01/18');
When i print this i get Thu Jun 01 1911 00:00:00 GMT+0530 (India Standard Time) but the system is actually 3:42 P.M
Use the current date to retrieve the time and include that in the new date. For example:
var now = new Date,
timenow = [now.getHours(),now.getMinutes(),now.getSeconds()].join(':'),
dat = new Date('2011/11/30 '+timenow);
you must give the time:
//Fri Nov 11 2011 00:00:00 GMT+0800 (中国标准时间)
alert(new Date("11/11/11"));
//Fri Nov 11 2011 23:23:00 GMT+0800 (中国标准时间)
alert(new Date("11/11/11 23:23"));
What do you want? Just the time? Or do you want to define a format? Cu's the code expects this format for date: dd/mm/yyyy, changed this to yyyy/mm/dd
Try this:
function formatDate (input) {
var datePart = input.match(/\d+/g),
year = datePart[0],
month = datePart[1], day = datePart[2],
now = new Date;
document.write(new Date(year+'/'+month+'/'+day+" " + now.getHours() +':'+now.getMinutes() +':'+now.getSeconds()));
}
formatDate ('2010/01/18')
Output:
Mon Jan 18 2010 11:26:21 GMT+0100
Passing a string to the Date constructor is unnecessarily complicated. Just pass the values in as follows:
new Date(parseInt(year, 10), parseInt(month, 10), parseInt(day, 10))
You're creating a Date() object with no time specified, so it's coming out as midnight. if you want to add the current date and time, create a new Date with no arguments and borrow the time from it:
var now = new Date();
var myDate = new Date(parseInt(year, 10), parseInt(month, 10), parseInt(day, 10),
now.getHours(), now.getMinutes(), now.getSeconds())
No need to strip the last two characters off the year. "2010" is a perfectly good year.

Categories

Resources