I have the following code
datePicker.change(function(){
dateSet = datePicker.val();
dateMinimum = dateChange();
dateSetD = new Date(dateSet);
dateMinimumD = new Date(dateMinimum);
if(dateSetD<dateMinimumD){
datePicker.val(dateMinimum);
alert('You can not amend down due dates');
}
})
dateSet = "01/07/2010"
dateMinimum = "23/7/2010"
Both are UK format. When the date objects are compared dateSetD should be less than dateMinimumD but it is not. I think it is to do with the facts I am using UK dates dd/mm/yyyy. What would I need to change to get this working?
The JavaScript Date constructor doesn't parse strings in that form (whether in UK or U.S. format). See the spec for details, but you can construct the dates part by part:
new Date(year, month, day);
MomentJS might be useful for dealing with dates flexibly. (This answer previously linked to this lib, but it's not been maintained in a long time.)
This is how I ended up doing it:
var lastRunDateString ='05/04/2012'; \\5th april 2012
var lastRunDate = new Date(lastRunDateString.split('/')[2], lastRunDateString.split('/')[1] - 1, lastRunDateString.split('/')[0]);
Note the month indexing is from 0-11.
var dateString ='23/06/2015';
var splitDate = dateString.split('/');
var month = splitDate[1] - 1; //Javascript months are 0-11
var date = new Date(splitDate[2], month, splitDate[0]);
Split the date into day, month, year parts using dateSet.split('/')
Pass these parts in the right order to the Date constructor.
Yes, there is problem with the date format you are using. If you are not setting a date format the default date that is used is 'mm/dd/yy. So you should set your preferred date formate when you create it as following when you create the date picker:
$(".selector" ).datepicker({ dateFormat: 'dd/mm/yyyy' });
or you can set it later as:
$.datepicker.formatDate('dd/mm/yyyy');
When you try to create a date object:
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Example:
dateSetD = new Date(dateSet.year, dateSet.month, dateSet.day);
Note: JavaScript Date object's month starts with 00, so you need to adjust your dateset accordingly.
Related
I'm using devExtreme dxScheduler and i'm trying to display meetings after fetching them from api, the problem is that i can't recreate the original date format ("YYYY-MM-DDThh:mm:ssZ") since i'm getting the dates as timestamp.
Here is how it's stores :
var startDate = moment("2021-05-24T16:30:00.000Z").valueOf()
// 1621873800000
Here is what i'm trying to do to recreate the format:
var startDate = moment(new Date(startDate)).format("YYYY-MM-DDThh:mm:ssZ")
//"2021-05-24T07:30:00+03:00"
Notice that the original date ("2021-05-24T16:30:00.000Z") and the formatted date ("2021-05-24T07:30:00+03:00") are different ...hence the calendar do not displays them.
Looks like the date is being converted into your local timezone, thus the difference. You may need to add Moment Timezone to be able to get the timezone back in to recreate it to the format you need. Also consider adding utc() before the format to bring it to Zulu time.
Fix 1
I see from the DevExtreme page that it needs to be displayed within this format:
currentDate: new Date(2021, 4, 27)
Maybe you need to format it before adding it like this:
var check = moment("2021-05-24T16:30:00.000Z", 'YYYY/MM/DD');
var month = check.format('M');
var day = check.format('D');
var year = check.format('YYYY');
console.log(month,day,year);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
And then in your dxScheduler add the property like this:
currentDate: new Date(year, month, day);
Fix 2
If that's not the problem, you can install moment-timezone
var a = moment.utc("2013-11-18 11:55").tz("Asia/Taipei");
var b = moment.utc("2013-11-18 11:55").tz("America/Toronto");
a.format(); // 2013-11-18T19:55:00+08:00
b.format(); // 2013-11-18T06:55:00-05:00
a.utc().format(); // 2013-11-18T11:55Z
b.utc().format(); // 2013-11-18T11:55Z
In this example, you first create moment.utc("2013-11-18 11:55") object in UTC, and then change its timezone to specified. This also works if you create the object in your default timezone: moment("2013-11-18 11:55").
Note that created moments have equal UTC time because these moments were created in a default timezone.
Turns out that displaying a calendar event with DevExtreme requires only to use regular date object.... so no need to do anything spacial.
I am trying to read all dates in a table and see if those dates are old dates than current date time and if those are old dates then highlight those dates with some color.
Here is my Javascript code
$(".ticket-gird-td-duedate").each(function(i, e) {
debugger;
var dueDateAsString = $(e).text();
console.log(dueDateAsString);
var dueDate = new Date(dueDateAsString);
var currentdate = new Date();
if (dueDate < currentdate) {
//mark date in red color
console.log("I need to change color for this date as this is past date" + dueDate);
}
});
Problem here is dueDateAsString comes as "07/10/2017 18:30 PM"
And when I am doing
new Date("07/10/2017 18:30 PM")
it fails with invalid date error
Invalid Date
How can I convert my string date to Javascript date and proceed to compare it with current date?
That isn't a valid date, as you either have 24hr format or AM|PM 12hr format.
This works:
new Date('07/10/2017 18:30'); // No 'PM' after the 24hr time
Also note that JS dates are mutable, so todayDate and check will hold the same date value, but check will be a number.
You call this one first
todayDate.setDate(todayDate.getDate() - 5);
It will update todayDate to 5 days ago. Then you just assign it to check or you todayDate further.
var check = todayDate;
Hope this helps.
You can do this by using moment.js library (yet another terrific way to achieve date parsing).
Moment.Js library is freely available. You can use either a minified or full version of this library as you require. In this
library all the operations are performed on a moment object so the
date or time is stored in this library as a moment object only. So
this moment object is the core of this entire library. You can find
this library at Moment.js site's home page.
Add momentjs library reference into your project - https://momentjs.com/downloads/moment.js
updated code with moment.js would be:
var todayDate = new moment().format("MM/DD/YYYY h:mm:ss a");
var yesterday = todayDate.toLocaleString();
var check = moment(todayDate, "MM/DD/YYYY h:mm:ss a").add('days', -5);
alert("Your Old Date is- " + todayDate);
alert(check);
alert("Your Old Date is- " + yesterday);
JavaScript fiddle
I have this application where I want to use you date, but the problem is that the date is not working as I expect.
I create a date object like this:
// Get today's date
today: function () {
// Create a new date
var date = new Date();
// Set to midnight
date.setHours(0, 0, 0, 0);
// Return our date
return date;
},
and If I output that date in my view I get yesterdays date at 23:00 hours....
Which looks like this:
2015-07-08T23:00:00.000Z
Does anyone know how I can get the date to be formatted properly?
Update
Just to elaborate a bit, I want to use the date to compare against records in the database. These records have the date applied to them, because the JavaScript is showing the local date time, it is not comparing correctly. Also there is a case where I am saving that date and I don't want it to save the local date.
based on your culture setting you can use the
date.toLocaleDateString()
this will give localized string format back
date.toUTCString();
date.toLocaleString();
date.toLocaleDateString();
date.toDateString();
date.toISOString();
Find your answer here :) And the best option is to use momentjs http://momentjs.com/
So, I ended up creating this function:
// Converts a date to a timeStamp
this.convertToTimeStamp = function (dateTime) {
// Get just the date
var date = dateTime.toDateString();
// Get the timestamp
var timeStamp = Date.parse(date);
// Return our timeStamp
return timeStamp;
};
If my understanding is correct, that should create the same date no matter what timezone / locale you are in.
I need to convert date to Java epoch and then read it and convert back. Not sure what I'm doing wrong here?
var date = new Date('1/3/2013');
var timeStamp = date.getTime();
console.log(timeStamp);
var revertDate = new Date(timeStamp);
console.log(revertDate.getDate()+'/'+revertDate.getMonth()+'/'+revertDate.getFullYear());
The output is 3/0/2013 instad 1/3/2013?
fiddle link
You've got two problems here:
The Date constructor is assuming M/d/yyyy format - whereas you're logging d/M/yyyy format. Personally I'd suggest using an ISO-8601 format if at all possible: yyyy-MM-dd
You're not taking into account the fact that getMonth() returns a 0-based value
For the formatting side, you'd be better off using toISOString or something similar, rather than doing the formatting yourself.
(Note that looking at the documentation for the Date constructor it's not clear that the code you've got should work at all, as it's neither an RFC822 nor ISO-8601 format.)
Neither of the problems are to do with converting between Date and a numeric value. If you change your logging, you'll see that clearly:
var date = new Date('1/3/2013');
var timeStamp = date.getTime();
console.log(date);
var revertDate = new Date(timeStamp);
console.log(revertDate);
var date = new Date('1/3/2013');
The Date constructor is parsing this given string this way:
Month / Day / Year
So, in this case, Month is 1, Day is 3 and Year is 2013. What's going on there? Well that's quite simple. This Gregorian representation of a date(which is specifically Day / Month / Year ) isn't the one used by the Date constructor, so it will parse the 1(the month) as January, the 3 as the third day of the month(the third of Jan) and the year correctly, the 2013. Now, due to its 0-based indexing, the constructed Date object will return a month which is n-1 among the one provided. That's why you're getting 3/0/2013. It is the third day(3) of the month 0(which is January) of 2013. If you want to get your real date you have to do this:
var date = new Date('3/1/2013');
console.log(date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear());
I am facing a weird problem while initializes javascript date object,no matter what I initialize to it shows the date as 1 JAN 1970 05:30;
this is the way I try to initialize
var d=new date(27-02-1989);
alerting 'd' shows 1 JAN 1970.....,also sometimes it takes a date passed from the database but in the format as mm/dd/yyyy not in the format I want i.e dd/mm/yyyy
This problem has suddenly popped-up, as everything was working smooth couple of days ago,but today after opening the project (after 2 days) this issue is irritating me
I see you've accepted an answer, but it isn't the best you can do. There is no one format that is parsed correctly by all browsers in common use, the accepted answer will fail in IE 8 at least.
The only safe way to convert a string to a date is to parse it, e.g.
var s = '27-02-1989';
var bits = s.split('-');
var date = new Date(bits[2], --bits[1], bits[0]);
// Transform your european date in RFC compliant date (american)
var date = '27-02-1989'.split('-').reverse().join('-');
// And this works
var d = new Date( date );
Proof:
You're doing an initialization with a negative integer value (27-02-1989 == -1964). The Date object's constructor takes arguments listed here.
If you want to pass strings, they need to be in an RFC2822-compliant format (see here).
according to here you can try:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day [, hour, minute, second, millisecond ])
so for your case use (edit: You need to remember that months are zero based)
var d = new Date(1989,01,27);
pleas notice - use Date (capital D)
First of all
var d=new date(27-02-1989);
is totaly wrong expression in javascript, moreover even if we rewrites it more correctly:
var d=new Date('27-02-1989');
there is no way to parse this date string natively in js.
Here solutions you can try:
transform string to ISO8601: YYYY-mm-dd, this can be parsed by most modern broswers, or you can use many js libraries for polyfill
split string string by '-' and then use Date constructor function new Date(year, month-1, day)
split string and use setDate, setMonth, setYear method on new Date() object
Note that in last two methods you need to deduct 1 from month value, because month is zero-based (0 stands for January, 11 for December)