I've seen a few questions about this, however none seem to be a universal solution for all browsers.
On my webpage I'm fetching a MYSQL Timestamp 'YYYY-MM-DD hh:mm:ss' in UTC. However, I need to convert this timestamp in Javascript to display just time in local meridian format... (i.e.. 8:00 pm).
The closest solution i found was appending 'UTC' to the MySQL timstamp string and creating a date object like that. However, this solution doesn't work in Safari. In anyone's knows of a solution please let me know.
Thank you in advance.
First convert MySql date string into JavaScript Date object. Then convert this gmt date object to local date object.
function mysqlGmtStrToJSDate(str) {
var t = str.split(/[- :]/);
// Apply each element to the Date function
return new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
}
function mysqlGmtStrToJSLocal(str) {
// first create str to Date object
var g = mysqlGmtStrToJSDate(str);
//
return new Date(g.getTime() - ( g.getTimezoneOffset() * 60000 ));
}
Converting the MySQL timestamp to Date object in JS and then using getTimezoneOffset() is a valid way to do it. According to the ECMAScript specification the Date should look something like this : YYYY-MM-DDTHH:MM:SS, so you should format the date correctly ( string replace(' ', 'T') )
If it is still not working, this is a list of date formats working across all browsers as described here
var d = new Date(2011, 01, 07);
var d = new Date(2011, 01, 07, 11, 05, 00);
var d = new Date("02/07/2011");
var d = new Date("02/07/2011 11:05:00");
var d = new Date(1297076700000);
var d = new Date("Mon Feb 07 2011 11:05:00 GMT");
Related
I'm new in Javascript, In PHP file I have script like so,
$JsonFormat = sprintf(
'\/Date(%s%s)\/',
$dateTime->format('U') * 1000,
$dateTime->format('O')
);
$dateTime->format('U') = Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
$dateTime->format('O') = Difference to Greenwich time (GMT) in hours
which returns a data like this, and works fine.
/Date(1542798236000+0800)/
I tried to redo the code using javascript like so,
var dt = new Date();
var newDate = new Date(Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate()));
var newDate = '\/Date(' + newDate.getTime() + '+0800)\/';
But it returns like this
/Date(1542758400000+0800)/
In the API I want to access, it says "Login out of date" which means the datetime probably not correct.
Timezone: "Asia/Manila"
How do I manage to get the correct datetime.
$scope.notAvailableDayClick=function(val1,date){
console.log("day clcik")
var startDate=$filter('date')(date,'yyyy-MM-dd')
var endDate=new Date(startDate)
endDate.setMinutes(59)
endDate.setHours(23)
}
date is 2015-01-16
if I do this
new Date(date)
Thu Jan 15 2015 16:00:00 GMT-0800 (Pacific Standard Time)
So I have to go with AngularJS
var startDate=$filter('date')(date,'yyyy-MM-dd')
but now I need startDate.getTime(), error occur I think it takes it as a String
As per angular docs the filter returns a String in requested format. Date constructor accepts ISO8601 formats usually although some browsers support many formats as I remember. Probably your format yy-MM-dd is not supported.
I hope the variable date is a valid Date object, in that case why don't you use it instead of the formatted string you made with angular filter?
var endDate = new Date(date);
endDate.setMinutes(59);
endDate.setHours(23);
Also you have a Date constructor that accepts the format
new Date(year, month[, date[, hour[, minutes[, seconds[, milliseconds]]]]]);
So if what you have in hand is 2015-01-16 you can get midnight of that day with:
var startDate = "2015-01-16";
var year = parseInt(startDate.split('-')[0], 10);
var month = parseInt(startDate.split('-')[1], 10) - 1;
var year = parseInt(startDate.split('-')[2], 10);
var endDate = new Date(year, month, date, 23, 59);
Just use the original date to create endDate not the angular filtered version
var endDate=new Date(date);
endDate.setMinutes(59);
endDate.setHours(23);
Best option is to use ISO-String, because Google Chrome supports this format: MM-dd-yyyy. In Mozilla this format gives Invalid Date.
new Date('MM-dd-yyyy')
So using Iso-String in Angular, it can done as follows:
new Date($filter('date')(yourdDate,'yyyy-MM-ddTHH:mm:ss.sssZ'))
I'm trying to display a date with format "MMM. dd HH:mm:ss.nnn". It is rendering it incorrectly in IE and I have spent quite some time and I can't figure out why I can't get this to work.
I know that Date.UTC returns the number of miliseconds in a Date object since Jan 1, 1970. So,
var newDate = new Date(Date.UTC(year, month[, date[, hrs[, min[, sec[, ms]]]]])
newDate.toString("MMM. dd HH:mm:ss.")+row.timestamp.getMilliseconds();
will work.
Example:
var newDate = new Date(Date.UTC(1950, 10, 10, 10, 09, 09, 100));
row.timestamp_f = newDate.toString("MMM. dd HH:mm:ss."); // Output => Nov. 10 05:09:09.
But, I am interating this from a jquey.each function so the date string that I am working with is an ISO 8601: "2013-03-12T15:14:10.483". So, this is what I have in mind.
var numMilisecond = Date.parse(row.timestamp);
var newDate = new Date(numMilisecond);
row.timestamp_f = newDate.toString("MMM. dd HH:mm:ss."); // Output => Dec. 31 19:00:00.
row.timestamp is from a JSON response
{"timestamp":"2013-03-12T15:14:10.483" ...}
Why doesn't the code work? Date.parse should return the number of miliseconds since Jan 1, 1970 and then I create a new Date obj and then convert it to string just like the code in the first snipet. What am I doing wrong?
Thanks.
Date.toString shouldn't accept any arguments. If you want a true date-formatting solution, you'll need to use a plugin or roll your own.
var shortmonths = ['Jan','Feb','Mar','Apr',]; // remaining months are left as an exercise for the reader
row.timestamp_f = shortmonths[newDate.getMonth()]
+ ". "+newDate.getDate() + " "
+ newDate.toLocaleTimeString() + ".";
Any idea why this function doesn't work properly in Internet Explorer?
function days_between(check_in, check_out)
{
var oneDay = 24*60*60*1000;
var firstDate = new Date(check_in);
var secondDate = new Date(check_out);
var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay));
return diffDays;
}
in internet explorer it shows NaN as result.
im calling this function in this date format
var check_in = "2012-02-09";
var check_out = "2012-02-12";
var range = days_between(check_in, check_out);
Regards
IE doesn't support Date.parse or passing "2012-02-09" (with ISO dates) to new Date, you need to parse it yourself and pass new Date( 2012, 1, 9 ) or use a Date.parse shim for ISO dates
The date format you're passing (yyyy-mm-dd) isn't supported by Date. See the note here that says it must be in a format parsable by parse. See here for acceptable parse formats: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/parse
You have problem in creating the Date Object
Date objects are created with the Date() constructor.
There are four ways of instantiating a date:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Most parameters above are optional. Not specifying, causes 0 to be passed in.
Once a Date object is created, a number of methods allow you to operate on it. Most methods allow you to get and set the year, month, day, hour, minute, second, and milliseconds of the object, using either local time or UTC (universal, or GMT) time.
All dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC) with a day containing 86,400,000 milliseconds.
Some examples of instantiating a date:
var today = new Date()
var d1 = new Date("October 13, 1975 11:13:00")
var d2 = new Date(79,5,24)
var d3 = new Date(79,5,24,11,33,0)
(Taken from http://www.w3schools.com/js/js_obj_date.asp)
You are giving the date arguments in an incorrect format. You can expect javascript to support these formats:
MM-dd-yyyy
yyyy/MM/dd
MM/dd/yyyy
MMMM dd, yyyy
MMM dd, yyyy
To fix your immediate problem, you can use replace() to format your arguments.
function days_between(check_in, check_out)
{
var firstDate = new Date(check_in.replace('-' , '/'));
var secondDate = new Date(check_out.replace('-' , '/'));
var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime()) / 86400000);
return diffDays;
}
And by the way, you can replace oneDay with a constant.
I am struggling to find out the beginning of day factoring in timezones in javascript. Consider the following:
var raw_time = new Date(this.created_at);
var offset_time = new Date(raw_hour.getTime() + time_zone_offset_in_ms);
// This resets timezone to server timezone
var offset_day = new Date(offset_time.setHours(0,0,0,0))
// always returns 2011-12-08 05:00:00 UTC, no matter what the offset was!
// This has the same issue:
var another_approach_offset_day = new Date(offset_time.getFullYear(),offset_time.getMonth(),offset_time.getHours())
I expect when i pass a Pacific Timezone offset, to get: 2011-12-08 08:00:00 UTC and so on.
What is the correct way to achieve this?
I think that part of the issue is that setHours method sets the hour (from 0 to 23), according to local time.
Also note that I am using javascript embedded in mongo, so I am unable to use any additional libraries.
Thanks!
Jeez, so this was really hard for me, but here is the final solution that I came up with the following solution. The trick was I need to use setHours or SetUTCHours to get the beginning of a day -- the only choices I have are system time and UTC. So I get the beginning of a UTC day, then add back the offset!
// Goal is given a time and a timezone, find the beginning of day
function(timestamp,selected_timezone_offset) {
var raw_time = new Date(timestamp)
var offset_time = new Date(raw_time.getTime() + selected_timezone_offset);
offset_time.setUTCHours(0,0,0,0);
var beginning_of_day = new Date(offset_time.getTime() - selected_timezone_offset);
return beginning_of_day;
}
In JavaScript all dates are stored as UTC. That is, the serial number returned by date.valueOf() is the number of milliseconds since 1970-01-01 00:00:00 UTC. But, when you examine a date via .toString() or .getHours(), etc., you get the value in local time. That is, the local time of the system running the script. You can get the value in UTC with methods like .toUTCString() or .getUTCHours(), etc.
So, you can't get a date in an arbitrary timezone, it's all UTC (or local). But, of course, you can get a string representation of a date in whatever timezone you like if you know the UTC offset. The easiest way would be to subtract the UTC offset from the date and call .getUTCHours() or .toUTCString() or whatever you need:
var d = new Date();
d.setMinutes(d.getMinutes() - 480); // get pacific standard time
d.toUTCString(); // returns "Fri, 9 Dec 2011 12:56:53 UTC"
Of course, you'll need to ignore that "UTC" at the end if you use .toUTCString(). You could just go:
d.toUTCString().replace(/UTC$/, "PST");
Edit: Don't worry about when timezones overlap date boundaries. If you pass setHours() a negative number, it will subtract those hours from midnight yesterday. Eg:
var d = new Date(2011, 11, 10, 15); // d represents Dec 10, 2011 at 3pm local time
d.setHours(-1); // d represents Dec 9, 2011 at 11pm local time
d.setHours(-24); // d represents Dec 8, 2011 at 12am local time
d.setHours(52); // d represents Dec 10, 2011 at 4am local time
Where does the time_zone_offset_in_ms variable you use come from? Perhaps it is unreliable, and you should be using Date's getTimezoneOffset() method. There is an example at the following URL:
http://www.w3schools.com/jsref/jsref_getTimezoneOffset.asp
If you know the date from a different date string you can do the following:
var currentDate = new Date(this.$picker.data('date'));
var today = new Date();
today.setHours(0, -currentDate.getTimezoneOffset(), 0, 0);
(based on the codebase for a project I did)
var aDate = new Date();
var startOfTheDay = new Date(aDate.getTime() - aDate.getTime() % 86400000)
Will create the beginning of the day, of the day in question
You can make use of Intl.DateTimeFormat. This is also how luxon handles timezones.
The code below can convert any date with any timezone to its beginging/end of the time.
const beginingOfDay = (options = {}) => {
const { date = new Date(), timeZone } = options;
const parts = Intl.DateTimeFormat("en-US", {
timeZone,
hourCycle: "h23",
hour: "numeric",
minute: "numeric",
second: "numeric",
}).formatToParts(date);
const hour = parseInt(parts.find((i) => i.type === "hour").value);
const minute = parseInt(parts.find((i) => i.type === "minute").value);
const second = parseInt(parts.find((i) => i.type === "second").value);
return new Date(
1000 *
Math.floor(
(date - hour * 3600000 - minute * 60000 - second * 1000) / 1000
)
);
};
const endOfDay = (...args) =>
new Date(beginingOfDay(...args).getTime() + 86399999);
const beginingOfYear = () => {};
console.log(beginingOfDay({ timeZone: "GMT" }));
console.log(endOfDay({ timeZone: "GMT" }));
console.log(beginingOfDay({ timeZone: "Asia/Tokyo" }));
console.log(endOfDay({ timeZone: "Asia/Tokyo" }));