I am using javascript date and I am trying to get it in my own format(YYYY-MM-DD). However, I could manage the format but the problem here is I am getting a day ahead. For eg: if the day is 3(today), here with this code I am getting 4.
let currentDate = new Date(currentForm['dobs']);
let middleDate = currentDate.toLocaleDateString().split('-');
let finalDate = middleDate[0] + '-' + middleDate[1] + '-' + (middleDate[2] - 1);
console.log(finalDate);
Here, in currentDate I am getting date as: 2051-06-30T18:15:00.000Z
But, in finalDate, I am getting 2049-6-31
Ignoring the syntax, why am I getting a day ahead ? How to achieve a correct date ??
I used to have this question few years ago and the reason is really simple. It's because of the 'Z' character at the end of the date value, because for the .toLocaleDateString() function(given that you haven't specified parameters, here is more info) implies this value lies in the UTC+0 zone and for some kind of reason that is always throwing you one day a head.
Solution:
To solve this you have many options, but maybe the simplest one is to format the date by yourself like this:
function lz(n){return n<10 ? '0'+n : n}
var d = new Date('2019-01-01T00:00:00Z');
var formatted = d.getUTCFullYear()+'-'
+ lz(d.getUTCMonth()+1)+'-'
+ lz(d.getUTCDate())+' '
+ lz(d.getUTCHours())+':'
+ lz(d.getUTCMinutes())+':'
+ lz(d.getUTCSeconds());
Or you can use third-party libraries like moment.js which, by the way, is pretty popular. Here is a link for more info.
Edit:
My apologies I was omitting one part of my code since I took it directly from one of my projects. Please follow the above code or test it in this fiddle.
As per #Alfredo Zamudio answer, I tried to remove that 'Z' attached at the end of my date value and after that everything ok.
let currentDate = new Date(currentForm['dobs']);
let newDate = currentDate.toISOString().replace('Z', '');
After these lines of code my issue was solved and then I used simple technique to format date.
let formattedDate = newDate.getFullYear() + '-' + newDate.getMonth() + '-' + newDate.getDate();
Thanks to all !
Related
So I'm making a reservations form, and I'll store all the data including the date in the database, but I don't want the certain dates to show if certain time has pass today, (example 12:00 CET), or if the date is unavaliable, either due to date from database-tbl_unavaliable or due to reaching max amnout of reservations for the day (10 for example).
So far after a few hours of searching I've found only this on SO, I don't know if the thing i want is doable or not with php since it's kind of the only thing I currently somewhat know and I'm still currently learning it. I do not know anything of JavaScript. But is there a kind of way to maybe get a $variable with php and make that a condition in JavaScript or something similar?
<script>
function getISODate(){
var d = new Date();
return d.getFullYear() + '-' +
('0' + (d.getMonth()+1)).slice(-2) + '-' +
('0' + d.getDate()).slice(-2);
}
window.onload = function() {
document.getElementById('minToday').setAttribute('min',getISODate());
}
</script>
<p>Select date(must be on or after today)<input type="date" id="minToday"></p>
I need to convert my date to mm-dd-yyyy format. So I used a method like this:
var dt=new Date(2016-06-21);
var ddte='';
ddte=(("0" + (dt.getMonth() + 1)).slice(-2))+"-"+(("0" + dt.getDate()).slice(-2))+"-"+dt.getFullYear();
It works fine in my local timezone (GMT+05:30). But when I change my timezone to GMT -5:00, it gives the wrong result: 06-20-2016. The result I want is 06-21-2016.
Can anyone please explain the problem?
How can I get the correct result?
Is it a bug?
Your date passed to Date() constructor will be treated as UTC time zone. Getting the time with Date.getMonth() will get your local time zone. You're probably looking for Date.getUTCMonth().
var dt=new Date("2016-06-21");
var ddte='';
ddte=(("0" + (dt.getUTCMonth() + 1)).slice(-2))+"-"+(("0" + dt.getUTCDate()).slice(-2))+"-"+dt.getUTCFullYear();
console.log(ddte);
Though in this case I see no use for using Date at all; this should suffice:
var parsedDate = "2016-06-21".replace(/(\d{4})-(\d{2})-(\d{2})/, "$2-$3-$1");
console.log(parsedDate);
It isn't a bug. It's just how time zones work (it isn't the same calendar day everywhere in the world at the same time).
If you don't actually want advanced date features (it seems you only want some good old string manipulation) my tip is to just not use Date in the first place.
var parts = "2016-06-21".split("-");
var mdy = parts[1] + "-" + parts[2] + "-" + parts[0];
Add some error checking and you're done.
I am getting data through Django api into my web application and the date return is "2015-09-10T00:00:00Z", is there a javscript function that can turn this into format like 2015-09-10
var date = new Date("2015-09-10T00:00:00Z");
var result = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
This is cumbersome and error prone, also it removes the leading 0 for the month and day. Take a look at this js library: mement.js, it should provide whatever you need to manipulate the time.
It's very light weight and easy to use.
Is there a way to get date and time in JS?
I searched in google and saw ways to get the date appart and time appart but not together.
I have a field that calls "Date Time" and i need to show data -12 hours so i need to figure out how to save datetime.
Can someone help?
Use javaScript Date object to work with date and time.
alert(new Date());
Use new Date();
var x = new Date();
You can also fetch each value using .getDay() , .getMonth(), .getYear(), .getHours(), .getMinutes(), .getSeconds()
Like
x.getHours(); // Will give you hours.
use date object of javascript then adjust your date and time combinations
for example, create a function getdateTime which will return dateTime combinations
function getdateTime() {
var date = new Date();
var dataVal=date.getDate() +"/"+ (date.getMonth() + 1)+"/" + date.getFullYear() + ":" + date.getHours() + ":" + date.getMinutes();
return dataVal;
}
var datetime=getdateTime();
console.log("datetime:" +datetime);
output for example : datetime:18/2/2015:14:26
ie current date and time
since months starts from 0 to 11 you have to add 1 to get current month.
you can use other date functions depending upon your requirements.
so, i need format JSON date from this format
"9/30/2010 12:00:00 AM", it is MM/DD/YYYY HH:MM:SS to format like this : DD/MM/YYYY, so i dont need info about hours, min and sec, and i need replace months and days from json, i tried some different ways but it always failed
i need do this using jQuery
also i didnt find any answer to formating this date type, all i found was formating date like this :/Date(1224043200000)/
so anyone have idea?
you can create a Date Object from a string like so:
var myDate = new Date(dateString);
then you can manipulate it anyway you want, one way to get your desired output is:
var output = myDate.getDate() + "\\" + (myDate.getMonth()+1) + "\\" + myDate.getFullYear();
you can find more at this elated.com article "working with dates"
Unfortunately your "from" dateformat is not the one which is implementation-independent in JavaScript. And all the other formats depends on the implementation, which means even if this format would be understood by most of the implementation I/you can't be sure for example how the DD and MM order would be parsed (I am almost sure it would be local regional settings dependent). So I would recommend to use a 3rd party (or your hand written) date parser to get a Date object out of your input string. One such parser you can find here:
http://www.mattkruse.com/javascript/date/
Because your question is not 100% clear for me, it's possible that you have your date in the format of /Date(number)/ which suggests that you are calling an ASP.Net service from your jQuery code. In this case during the JSON parse you can convert it to a Date object:
data = JSON.parse(data, function (key, value) {
// parsing MS serialized DateTime strings
if (key == '[NAME_OF_DATE_PROPERTY_IN_THE_JSON_STRING]') {
return new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
// maybe new Date(parseInt(value.substr(6))) also works and it's simpler
}
return value;
});
The code below solved my problem:
var date = new Date(parseInt(d.data[i].dtOrderDate.replace("/Date(", "").replace(")/", ""), 10));
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
Try something like this :
var date = new Date(parseInt(jsonDate.substr(6)));
where jsonDate is variable that stores your date