I have a script that stores an action taken by a user. There's a column that contains datetime and originally I user NOW(), but that uses server time, which is a few hours off as compared to the user's actual time.
So I decided I'll use the time that I can get with JS. I've formatted it this way:
var now = new Date(),
isnow = now.getFullYear() + '-' + ('0' + (now.getMonth() + 1)).slice(-2) + '-' + ('0' + now.getDate()).slice(-2) + ' ' + ('0' + (now.getHours() + 1)).slice(-2) + ':' + ('0' + now.getMinutes()).slice(-2) + ':' + ('0' + now.getSeconds()).slice(-2);
I've tested and while the format works fine, the time is off by an hour. Is it because of the Daylight Savings Time? How do I get the actual local time for the user?
In your code wrote:
...('0' + (now.getHours() + 1)).slice(-2)...
Try to remove this plus one
Additional you can check if Day Savings Time with:
if (now.dst()) { alert ("Daylight savings time!"); }
Date.prototype.stdTimezoneOffset = function() {
var jan = new Date(this.getFullYear(), 0, 1);
var jul = new Date(this.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
Date.prototype.dst = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
}
Based at answer similar issue
You should use the toISOString() method to convert the Date object to the ISO-8601 standard format:
now.toISOString();
The ISO-8601 date format puts the time information into a universal form which includes optional timezone information (likely the source of your issues).
Related
I got a function which converts my timestamp into a date and looks like this:
delivery: function(created) {
var date = new Date(created * 1000);
var formattedDate = ('0' + date.getDate()).slice(-2) + '/' +
('0' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear() + ' ,' +
('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
return formattedDate;
}
now I want to display the date in MM/DD/YYYY for the american user which come to my site, so I would like to implement an if-clause, which firstly looks where the user comes from and then display the date in MM/DD/YYYY if he is from america, and if he is from europe in DD/MM/YYYY
Well in the SAPUI5 documentation I just saw this:
// The source value is given as timestamp. The used output pattern is "dd.MM.yyyy HH:mm": e.g. 22.12.2010 13:15
oType = new sap.ui.model.type.DateTime({source: {pattern: "timestamp"}, pattern: "dd.MMM.yyyy HH:mm"});
but I don't really understand how it works if I do oType.formatValue(created); its not working so maybe someone with more experience can explain me where I have to put my timestamp which is stored under "created"
What's wrong with simply using
delivery: function(created) {
var date = new Date(created * 1000);
return date.toLocaleDateString() + " " + date.toLocaleTimeString();
}
exactly?
EDIT: For clarity, I've supplied the whole function, not just the return statement
I have a grid in which each row has a PHP format('Y-m-d H:i:s') date displayed.I wanted to apply a javascript filter which will show only those rows which has timestamp past 36hrs.
Whats the best way to first get past 36hrs timestamp & then compare that timestamp with displayed PHP timestamp using javascript.
Till now I tried using below code to get past 36 timestamp
var mydate=new Date();
mydate.setHours(mydate.getHours()-36);
dateInPhpFormat=mydate.getFullYear()+'-'+mydate.getMonth()+'- '+mydate.getDate()+"
"+mydate.getHours()+":"+mydate.getMinutes()+":"+mydate.getSeconds();
When I print dateInPhpFormat it shows wrong date.
Any help would be appreciated .
The only thing that could be wrong is that Javascript gives you the month, day, minues and seconds without leading zero. Also months are zero based, so you need to add 1 to the month.
For example month In JS: 3, in PHP(with 'm'): 03
You can add this leading zero yourself, like this;
var mydate=new Date();
mydate.setHours(mydate.getHours()-36);
var month = ('0' + (mydate.getMonth() + 1)).substr(-2);
var day = ('0' + mydate.getDate()).substr(-2);
var hour = ('0' + mydate.getHours()).substr(-2);
var minute = ('0' + mydate.getMinutes()).substr(-2);
var second = ('0' + mydate.getSeconds()).substr(-2);
dateInPhpFormat = mydate.getFullYear() + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
This will give you a date string which is identical to php date('Y-m-d H:i:s')
JavaScript Date objects use zero based months for some reason. Try adding 1 to the month.
dateInPhpFormat = mydate.getFullYear() + '-' + (mydate.getMonth() + 1 ) +'-'+mydate.getDate() + " " + mydate.getHours() + ":" + mydate.getMinutes() + ":" + mydate.getSeconds();
This question already has answers here:
Convert date to another timezone in JavaScript
(34 answers)
How to initialize a JavaScript Date to a particular time zone
(20 answers)
Closed 9 years ago.
How can I force Browser to display all date objects to use Specific Timezone.Like passing Europe/London.Is there any way to do so??
Update
Here I want is that all Jquery Datepicker open date and time as per Specific Timezone instead of Client's Machine.
You can't "set" the timezone offset, it's a read only property that is based on system settings.
You can generate time and date values for any timezone offset by simply adding the client timezone offset, then adding whatever offset you want (note that javascript Date object's timezone offset has an opposite sense to the usual value, so you add both rather than subtracting one and adding the other).
e.g.
// Provide offsetInMintes to add to UTC to get required time,
// e.g. Nepal Standard Time is UTC +05:45 -> +345 minutes
function generateOffsetTime(offsetInMinutes) {
function z(n){return (n<10? '0' : '') + n;}
var d = new Date();
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() + offsetInMinutes);
return [z(d.getHours()),z(d.getMinutes()),z(d.getSeconds())].join(':');
}
alert('The time in Nepal is ' + generateOffsetTime(345));
Edit
You could add your own methods to Date.prototype:
Date.prototype.setOffset = function(offsetInMinutes, offsetName) {
this._offsetInMinutes = offsetInMinutes;
this._offsetName = offsetName;
};
Date.prototype.getOffsetFullDate = (function() {
var months = ('January February March April May June July ' +
'August September October November December').split(' ');
var days = 'Sunday Monday Tuesday Wednesday Thursday Friday Saturday'.split(' ');
return function() {
var d = new Date(+this);
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() + this._offsetInMinutes);
return days[d.getDay()] + ' ' + d.getDate() + ' ' + months[d.getMonth()] +
', ' + this.getFullYear();
}
}());
Date.prototype.getOffsetTime = (function() {
function z(n){return (n<10? '0' : '') + n;}
return function() {
var d = new Date(+this);
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() + this._offsetInMinutes);
return z(d.getHours()) + ':' + z(d.getMinutes()) + ':' +
z(d.getSeconds()) + ' ' + this._offsetName;
}
}());
var d = new Date();
d.setOffset(345, 'NST')
console.log(d.getOffsetFullDate() + ' ' + d.getOffsetTime());
Note that this keeps the date object's original timevalue, it adjusts values as they are retrieved so the timezone can be changed to get different values for the same date object, so you could continue with:
d.setOffset(600, 'AEST');
console.log(d.getOffsetFullDate() + ' ' + d.getOffsetTime());
d.setOffset(630, 'LHI');
console.log(d.getOffsetFullDate() + ' ' + d.getOffsetTime());
But I still think it's better to build your own date constructor that leverages the built in Date rather than extends it.
Moment.js is a great library which could help you to achieve this.
The anytime jQuery plugin by default displays with the current date/time. The current date is perfect, but I want to set the time to midnight/00:00:00 for one "DateTimePicker" and the day's ultimate second (23:59:59) for the second one. How to do that?
UPDATE
Interesting - that causes the following to display in the anytime datetimepicker:
Mon, 29 Apr 2013 07:00:00
(actually, I can't see the last zero, but I'm assuming that's what it is).
On clicking on the component (is this the correct terminology for a jQuery plugin component/control instance?), the text reverts to:
2013-04-29 15:39:33 (current local time).
I reckon the 7 am jazz shown first has something to do with the UTC differential between here and...Greenwich, I would guess (I'm in California), but the fact that it reverts to the current local time (instead of remaining at 7 am, which I'm sure could be tweaked to accommodate the hour differential) makes this only entertaining rather than exhale-inducing.
UPDATE 2
I'm awarding a bounty to Marcacci ASAP, but stil, an interesting addendum to all this: Based on that code, I was able to work out what was needed if I just want to get up to the current second (when the page was loaded), rather than up to the second before midnight of the current day, which normally would be quite a few hours in the future:
var d = new Date();
var t = new Time();
var s = ('0' + (t.getHour() + 1)).slice(-2) + ":" +
('0' + (t.getMinute() + 1)).slice(-2) + ":" +
('0' + (t.getSecond() + 1)).slice(-2);
return d.getFullYear() + "-" + ('0' + (d.getMonth() + 1)).slice(-2) + "-" + ('0' + d.getDate()).slice(-2) + s;
However, oddly enough, the text/anytime DateTimePicker is blank when I use this code - until I click on it! Then it populates as I would expect it to...???
The other one (the "Begin Date") component, displays its value (midnight on the first of the month):
var d = new Date();
return d.getFullYear() + "-" + ('0' + (d.getMonth() + 1)).slice(-2) + "-" + "01 00:00:00";
...just fine.
You should just be able to manually set the input's value to today at midnight, and the plugin will pick up from there.
$('#dateInput').val(function(){
var d = new Date();
d.setHours(0,0,0,0);
return d.toUTCString();
});
EDIT
This should put it into the format that you're using:
$('#dateInput').val(function(){
var d = new Date();
return d.getFullYear() + "-" + (d.getMonth()+1) + "-" + d.getDate() + " 00:00:00";
});
EDIT 2
OK, so it's VERY stubborn about the format, but I got it working:
$('#field1').val(function(){
var d = new Date();
return d.getFullYear() + "-" + ('0' + (d.getMonth()+1)).slice(-2) + "-" + ('0' + d.getDate()).slice(-2) + " 00:00:00";
});
Check out the jsfiddle here.
Try the following code:
HTML
<input type="text" id="first" />
<input type="text" id="second" />
JavaScript
// Current date and time
var date = new Date();
// Set time to 00:00:00
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
$("#first").val(date.toUTCString());
// Set time to 23:59:59
date = new Date(date.getTime() + 23*60*60*1000 + 59*60*1000 + 59*1000);
$("#second").val(date.toUTCString());
// Apply plugin
$("#first, #second").AnyTime_picker();
I need to output the current UTC datetime as a string with the following format:
YYYY/mm/dd hh:m:sec
How do I achieve that with Javascript?
You can build it manually:
var m = new Date();
var dateString = m.getUTCFullYear() +"/"+ (m.getUTCMonth()+1) +"/"+ m.getUTCDate() + " " + m.getUTCHours() + ":" + m.getUTCMinutes() + ":" + m.getUTCSeconds();
and to force two digits on the values that require it, you can use something like this:
("0000" + 5).slice(-2)
Which would look like this:
var m = new Date();
var dateString =
m.getUTCFullYear() + "/" +
("0" + (m.getUTCMonth()+1)).slice(-2) + "/" +
("0" + m.getUTCDate()).slice(-2) + " " +
("0" + m.getUTCHours()).slice(-2) + ":" +
("0" + m.getUTCMinutes()).slice(-2) + ":" +
("0" + m.getUTCSeconds()).slice(-2);
console.log(dateString);
No library, one line, properly padded
const str = (new Date()).toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");
It uses the built-in function Date.toISOString(), chops off the ms, replaces the hyphens with slashes, and replaces the T with a space to go from say '2019-01-05T09:01:07.123' to '2019/01/05 09:01:07'.
Local time instead of UTC
const now = new Date();
const offsetMs = now.getTimezoneOffset() * 60 * 1000;
const dateLocal = new Date(now.getTime() - offsetMs);
const str = dateLocal.toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");
With jQuery date format :
$.format.date(new Date(), 'yyyy/MM/dd HH:mm:ss');
https://github.com/phstc/jquery-dateFormat
Enjoy
I wrote a simple library for manipulating the JavaScript date object. You can try this:
var dateString = timeSolver.getString(new Date(), "YYYY/MM/DD HH:MM:SS.SSS")
Library here:
https://github.com/sean1093/timeSolver
Not tested, but something like this:
var now = new Date();
var str = now.getUTCFullYear().toString() + "/" +
(now.getUTCMonth() + 1).toString() +
"/" + now.getUTCDate() + " " + now.getUTCHours() +
":" + now.getUTCMinutes() + ":" + now.getUTCSeconds();
Of course, you'll need to pad the hours, minutes, and seconds to two digits or you'll sometimes get weird looking times like "2011/12/2 19:2:8."
Alternative to answer of #JosephMarikle
If you do not want to figth against timezone UTC etc:
var dateString =
("0" + date.getUTCDate()).slice(-2) + "/" +
("0" + (date.getUTCMonth()+1)).slice(-2) + "/" +
date.getUTCFullYear() + " " +
//return HH:MM:SS with localtime without surprises
date.toLocaleTimeString()
console.log(fechaHoraActualCadena);
Posting another script solution DateX (author)
for anyone interested
DateX does NOT wrap the original Date object, but instead offers an identical interface with additional methods to format, localise, parse, diff and validate dates easily. So one can just do new DateX(..) instead of new Date(..) or use the lib as date utilities or even as wrapper or replacement around Date class.
The date format used is identical to php date format.
c-like format is also supported (although not fully)
for the example posted (YYYY/mm/dd hh:m:sec) the format to use would be Y/m/d H:i:s eg
var formatted_date = new DateX().format('Y/m/d H:i:s');
or
var formatted_now_date_gmt = new DateX(DateX.UTC()).format('Y/m/d H:i:s');
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC