How can i convert day date (for example, 22 which stands for 1/22/2017) to Unix Timestamp (after conversion result needs to be 1485079018) in javascript.
I tried code below without luck.
var d = new Date();
var n = d.getDate();
var g = Math.round(new Date().getDate()/1000);
to Unix Timestamp (after conversion result needs to be 1485079018
The Unix timestamp 1485079018 is Jan 22 2017 at 09:56:58 UTC. Where are you getting that 09:56:58 from?
In terms of the problem, if I assume you actually want midnight UTC rather than 09:56:58, see comments:
var day = 22;
// Create the date (in UTC)
var dt = new Date(Date.UTC(2017, 0, day));
// Or not UTC, but then we get really far afield of Unix timestamps:
//var dt = new Date(2017, 0, day);
var ts = Math.round(dt / 1000);
console.log(ts);
Related
I have a string that looks like "01:12:33" which is HH:MM:SS format. How can I convert that to a time value in JS?
I've tried the new Date() constructor and setting the year and day values to 0, then doing getTime(), but I am not having any lucky.
Prefix it with a date:
var hms = "01:12:33";
var target = new Date("1970-01-01T" + hms);
console.log(target);
There target.getTime() will give you the number of milliseconds since the start of the day;
Or, if you need it to be today's date:
var now = new Date();
var nowDateTime = now.toISOString();
var nowDate = nowDateTime.split('T')[0];
var hms = '01:12:33';
var target = new Date(nowDate + 'T' + hms);
console.log(target);
There target.getTime() will give you the number of milliseconds since the epoch.
You can add the following function that does the job for you :
function getDateFromHours(time) {
time = time.split(':');
let now = new Date();
return new Date(now.getFullYear(), now.getMonth(), now.getDate(), ...time);
}
console.log(getDateFromHours('01:12:33'));
To be able to do this, there should be a conversion of the string in HH:MM:SS format to JavaScript time.
Firstly, we can use Regular Expression (RegEx) to properly extract the values in that string.
let timeString = "01:12:33";
Extract values with RegEx
let regExTime = /([0-9]?[0-9]):([0-9][0-9]):([0-9][0-9])/;
let regExTimeArr = regExTime.exec(timeString); // ["01:12:33", "01", "12", "33", index: 0, input: "01:12:33", groups: undefined]
Convert HH, MM and SS to milliseconds
let timeHr = regExTimeArr[1] * 3600 * 1000;
let timeMin = regExTimeArr[2] * 60 * 1000;
let timeSec = regExTimeArr[3] * 1000;
let timeMs = timeHr + timeMin + timeSec; //4353000 -- this is the time in milliseconds.
In relation to another point in time, a reference time has to be given.
For instance,
let refTimeMs = 1577833200000 //Wed, 1st January 2020, 00:00:00;
The value above is is the number of milliseconds that has elapsed since the epoch time (Jan 1, 1970 00:00:00)
let time = new Date (refTimeMs + timeMs); //Wed Jan 01 2020 01:12:33 GMT+0100 (West Africa Standard Time)
I have the following values;
//date is 14-Dec-2016
let day = 14;
let month = 12;
let year = 2016;
let TimezoneOffset = -480; //Timezone is GMT+0800 (Malay Peninsula Standard Time)
let time = 19:34; //in HHMM format
Based on these 5 variables, I would like to get the epoch time in javascript.
I am using node.js v6
You can create a date using the values, apply the timezone offset, then just get the time value:
var day = 14;
var month = 12;
var year = 2016;
var timezoneOffset = -480; //Timezone is GMT+0800 (Malay Peninsula Standard Time)
var time = '19:34'; //in HHMM format
// Create date using UTC methods but local values
var date = new Date(Date.UTC(year, month - 1, day, time.split(':')[0], time.split(':')[1]));
// Apply timezone offset to set to UTC time
date.setMinutes(date.getMinutes() + timezoneOffset);
var timeValue = date.getTime();
// milliseconds since 1970-01-01T00:00:00Z
console.log(timeValue);
// Check UTC date and time value
console.log(new Date(timeValue).toUTCString());
Note that variables starting with a capital letter are, by convention, reserved for constructors. And a time like "19:34" must be a string, not a number.
I am in GMT +2 timezone and Daylight saving time on.
My requirement is to ask user a date and convert it into UTC without DST consideration.
when I do console.log(new Date()),
it gives me "Wed Oct 26 2016 18:00:00 GMT+0300 (Turkey Daylight Time)"
I want to send server a UTC format date which server is going to save in Database.
var extractTime = new Date(timeof.edtime); //timeof.edtime contains date given by user.
var d = extractTime.getDate();
var m = extractTime.getMonth();
var y = extractTime.getFullYear();
var h = extractTime.getHours();
var mm = extractTime.getMinutes();
timeof.edtime = moment(new Date(y, m, d, h, mm)).utc().format("YYYY-MM-DD HH:mm");
After converting to utc, timeof.edtime is "2016-09-26 15:00" because it subtract 3 hours to go to GMT. (subtracted 2 hours of standard turkish time) (subtracted -1 of DST)
I want to subtract date to UTC by not considering DST and in our case my expectation is to get hour as "16:00" and not "15:00"
How to convert date to UTC without Daylight saving consideration.
any solution using moment js or jquery will be helpful.
I am testing on chrome.
by browsing through few link it says new Date() will give in standard time and doesn't consider DST consideration but this is not I observed and created plunk to reproduce new Date().toUTCString() consider DST as well, how to avoid subtraction of DST?
https://plnkr.co/edit/tjCOoJqXMHGzCD8B5LdL?p=preview
Inspired by this answer, you could make the time correction as follows:
function compensateDST(dt) {
var janOffset = new Date(dt.getFullYear(), 0, 1).getTimezoneOffset();
var julOffset = new Date(dt.getFullYear(), 6, 1).getTimezoneOffset();
var dstMinutes = dt.getTimezoneOffset() - Math.max(janOffset, julOffset);
dt = new Date(dt);
dt.setMinutes(dt.getMinutes() - dstMinutes);
return dt;
}
// Use your date here:
var extractTime = new Date('2016-10-26 18:00');
// Truncate to minute precision:
var extractTime = new Date(extractTime.getTime() - extractTime.getTime() % 60000)
console.log('Local time:', extractTime.toString());
console.log('UTC time before correction:', extractTime.toISOString());
// Compensate for the DST shift:
var extractTime = compensateDST(extractTime);
console.log('UTC time after correction:', extractTime.toISOString());
try this:
+180 is GMT+0300 (Turkey)
var x = new Date();
var newdate = new Date();
if((x.getTimezoneOffset()) != 180){
newdate = new Date(x.getTime() + (60000*(x.getTimezoneOffset()+180)));
}
console.log(newdate);
I tried many times to convert utc datetime to local datetime,and I have failed. My utc datetime format is
Fri Mar 8 23:12:27 UTC+0200 2013
Also my JavaScript code is
var time = Date(param_time);//param_time is /Date(1362866006646)/
And then time is being Sun Mar 10 00:21:54 UTC+0200 2013 I need to datetime as 2008-01-28T20:24:17Z because I will convert local datetime to pretty datetime.
http://ejohn.org/files/pretty.js
How can I do this ? I looked at many questions on stackoverflow but no one does it work. Thank you.
In order to format your Date correctly use toISOString():
var time = param_time.toISOString();
Note that param_time needs to be a valid Date object.
References
MDN: Date (sections: Syntax, Example: ISO 8601 formatted dates)
I rarely use javascript and all this date time conversion are mystery to me as well, javascript is a client side technology and all this "UTC" phrases means nothing (at least to me), as all the kind of getUTC...()/setUTC...() functions works in local time, the same is goes for all Date.to...String() functions, even the new Date() (that due to the docs) s'd be initialized in UTC, also give a local time.
However, if you have a (correct) date in UTC and wish to convert it to current (client side) local time, then you need getTimezoneOffset(), or shortly:
function UTCToLocalTime(d) {
var timeOffset = -((new Date()).getTimezoneOffset()/60);
d.setHours(d.getHours() + timeOffset);
return d;
}
var time = new Date(Date.parse('Fri Mar 8 23:12:27 UTC+0200 2013'));
alert(UTCToLocalTime(time)); // Sat Mar 9 01:12:27 UTC+0200 2013
//p.s. or...
function UTCToLocalTime2(d)
{
return new Date(d.toString().replace(/UTC.*/g,"") + d.getYear());
}
var timezone = "UTC+01:30";
var start = new Date();
if(timezone != "UTC"){
timezone = timezone.replace(/UTC/g,"");
znak = timezone.charAt(0);
timezone = timezone.replace(/[+|-]/g,"");
timezone = timezone.split(":");
//var start = new Date(start.toString() + " " + timezone);e.
//alert(start.toString());
if(znak == "+") start = new Date(start.getTime() + (timezone[0]*60*60000 + timezone[1] * 60000) );
if(znak == "-") start = new Date(start.getTime() - (timezone[0]*60*60000 + timezone[1] * 60000) );
}
var hours = start.getUTCHours();
var minutes = start.getUTCMinutes();
var seconds = start.getUTCSeconds();
var day = 10;
var month = 04;
var year = 2015;
var dateUtc = Date.UTC(year, month - 1, day + 1, 0, 0, 0);
> 1428710400000
var toDate = new Date(dateUtc);
> Fri Apr 10 2015 21:00:00 GMT-0300 (Hora oficial do Brasil)
I am trying to determine the time elapsed between 2 dates using javascript. An example would be: "I quit smoking on January 5, 2008 at 3 A.M., how many years, months, and hours has elapsed since I quit?".
So my thoughts were:
Get "quit" date
Get current date
Convert to time (milliseconds)
Find the difference
Create a new date using the difference
Extract the years, months, etc. from that date
Well, it is acting strange and I can't pin point why. Any insight?
//create custom test date
var d1 = new Date(2012, 8, 28, 13, 14, 0, 0);
//create current date
var d2 = new Date();
//get date times (ms)
var d1Time = (d1.getTime());
var d2Time = (d2.getTime());
//calculate the difference in date times
var diff = d2 - d1;
//create a new date using the time differences (starts at Jan 1, 1970)
var dDiff = new Date();
dDiff.setTime(diff);
//chop off 1970 and get year, month, day, and hour
var years = dDiff.getFullYear() - 1970;
var months = dDiff.getMonth();
var days = dDiff.getDate();
var hours = dDiff.getHours();
You can see it in action at this temporary host.
Why don't you just do the math to calculate the values? What you are putting into Date when you do dDiff.setTime(diff); is meaningless to you. That is just going to give you the date diff ms from the epoch.
Changing part of your code may solve your problem. jsfiddle
var start = new Date(0); // pivote point of date.
var years = dDiff.getFullYear() - start.getFullYear();
var months = dDiff.getMonth() - start.getMonth();
var days = dDiff.getDate() - start.getDate();
var hours = dDiff.getHours() - start.getHours();;
console.log(years, months, days, hours);
But you have to manipulate these values based on there value( they may come negative).
Date represents a particular point in time, not a timespan between two dates.
You are creating a new date by setting dDiff milliseconds ellapsed since the unix epoch.
Once you have the milliseconds ellapsed, you should extract the information you need by dividing it. See this question.
May I recomend taking a look at Moment.js?
This won't be accurate as it does not take into account the leap dayys. Other than that, it is working correctly and I don't see any problem. The time difference is roughly 6.5 days. Taking into account timezone and the fact that 0 is Jan 1st, the value I see is as expected.
The accurate solution would be to
Convert the time difference into days
Subtract the number of leap years elapsed since the specified date
Divide the remaining by 365 to get the number of days
Create an array with the day count of each month (without considering leap days) and loop through the elapsed months, subtracting the day count for the completed months. The number of iterations will be your month count
The remainder is your day count
Various notes:
new Date(2012, 8, 28, 13, 14, 0, 0); is 28 September 2012 13:14:00 (not August if you would it)
new Date(0) returned value is not a constant, because of the practice of using Daylight Saving Time.
dDiff.getMonth(); return 0 for Jan, 1 for Feb etc.
The begin of date (1 Jan 1970) begin with 1 so in difference you should subtract this.
I think the second point is your mistake.
According with your algorithm, try this:
// create date in UTC
//create custom test date
var dlocaltime = new Date(2012, 8, 28, 13, 14, 0, 0);
var d1 = new Date(dlocaltime.getUTCFullYear(),dlocaltime.getUTCMonth(), dlocaltime.getUTCDate(), dlocaltime.getUTCHours(),dlocaltime.getUTCMinutes(),dlocaltime.getUTCSeconds());
//create current date
var now = new Date();
var d2 = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
console.log(d1);
console.log(d2);
//get date times (ms)
var d1Time = (d1.getTime());
var d2Time = (d2.getTime());
//calculate the difference in date times
var diff = d2 - d1;
//create a new date using the time differences (starts at Jan 1, 1970)
var dDiff = new Date();
dDiff.setTime(diff);
//chop off 1970 and get year, month, day, and hour
var years = dDiff.getUTCFullYear() - 1970;
var months = dDiff.getUTCMonth();
var days = dDiff.getUTCDate()-1; // the date of new Date(0) begin with 1
var hours = dDiff.getUTCHours();
var minutes = dDiff.getUTCMinutes();
var seconds = dDiff.getUTCSeconds();
console.log("Years:"+years);
console.log("months:"+months);
console.log("days:"+days);
console.log("hours:"+hours);
console.log("minutes:"+minutes);
console.log("seconds:"+seconds);