Need methods other than Date.parse to parse a date string - javascript

I'm using JS to pull content from a table and create event list items on a page.
Im using Date.parse to compare the entry date to todays date, and only show events in the future, based on MM/DD/YY value from var eventDate.
<script>
today = new Date(); today.setDate(today.getDate() - 1);
eventDate = $(this).find("td:nth-child(3)").text().trim();
if (Date.parse(eventDate) > Date.parse(today)) {
//Do something...
}
</script>
I was thrilled to see how simple Date.parse was to use, then realized it only worked in Chrome (not in Firefox or IE). Any other ways to do this cross browser? Any thoughts would be appreciated. Thanks!

If you don't mind adding a library to your project; Moment.js provides a comprehensive set of formatting and query functions when handling dates not converted to the Date.parse input. It's fluent interface provides better readability for date comparison:
var dateFormat = "MM/DD/YY";
var today = moment().subtract(1, "day");
var eventDate = moment($(this).find("td:nth-child(3)").text().trim(), dateFormat);
if (moment(eventDate).isAfter(today)) {
// Do something
}

You can convert the date format like so:
'01/02/13'.replace(/^(\d{2})\/(\d{2})\/(\d{2})$/, '20$3-$1-$2')
// 2013-01-02

Related

Error converting selected date - Angular 8

I am making a filter between two dates, Start date and End date, the filter works perfect, it brings the data but it does not bring the complete data and it is because when selecting the dates and converting them to the format, it converts them but one day remains.
This way I am converting the dates:
FiltrarPorFechas(incial, final) {
this.ListaUsuarios = [];
const IniDate = new Date(incial);
const EndDate = new Date(final);
}
associate an image with debug and conversion:
As shown in the image, the initial and final dates arrive at the method thus "2019-07-10" and "2019-07-31" but when I try to convert them it puts them one day less as shown in the image.
I have tried to use moment formatDate and it does not work, I do not understand why and I do not want to add one day.
Somebody could help me ?
You may be potentially having an issue with Timezone. You could reset the time to 00:00:00 either using moment.js or from a normal Date() object.
Now, since your aim is to compare the times, you can use the diff() available from moment.js to achieve this. Please find the sample code below
(function() {
initial = '2019-07-09';
initial_formatted = moment(new Date(`${initial} 00:00:00`));
final = '2019-07-31';
final_formatterd = moment(new Date(`${final} 00:00:00`));
console.log(initial_formatted.diff(final_formatterd, 'days'));
// moment(new Date(`${incial} 00:00:00`)).format('YYYY-MM-DD HH:mm:ss');
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js" integrity="sha256-4iQZ6BVL4qNKlQ27TExEhBN1HFPvAvAMbFavKKosSWQ=" crossorigin="anonymous"></script>
More info
Moment diff()
Date Object set() method

Check whether the Date exists (30th / 31th day) [duplicate]

This question already exists:
Checking the validity of a date [duplicate]
Closed 6 years ago.
how to check whether the 30 or 31th day of a month does exist or not.
31.09.2016 doesn't exist but will be shown as 01.10.2016 in Java and Javascript. Even with the correct locales etc. Any solutions in javascript or java is welcome since an ajax request can solve this as well.
Thanks in advance
I think you should use the momentjs library for any kind of date manipulation in javascript: MomentJS
var date = moment('31.09.2016','DD.MM.YYYY');
console.log(date.isValid()); // This will print false in case of an invalid date
Edit: Created a plunker so you can try it out: plunker example
. Check the javascript console
The answer from #nagyf is pretty good for js, on the java side you should set the leninent property to false in the DateFormat and then you will get an ParseException if the date is invalid.
Example:
final String d = "31/09/2016";
final DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.setLenient(false);
final Date parsDate = df.parse(d);
System.out.println(d);
Here is solution for Java
try{
String date = "31/9/2016";
Data d = new Date();
DateFormat df = new SimpleDateFormat("đd/MM/yyyy");
df.setLenient(false);
d = df.parse(date);
catch(ParseException ex){
System.out.println("Invalid Date");
}
An alternative way of checking lastDay given vs what is actually on calendar would be if you are working with a valid date and a given lastDay : (not in javascript in groovy/java)
int day=31
Date givenDate = new Date()
Calendar cal = Calendar.instance
cal.setTime(givenDate)
int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH)
if (day > lastDay) {
// fail throw exception
}
//otherwise good to go
java.time
The YearMonth class is handy for this. This object can provide a LocalDate object representing the last day of the month. You can ask that object for its day-of-month number.
int numberOfLastDay =
YearMonth.of( 2016 , Month.SEPTEMBER )
.atEndOfMonth()
.getDayOfMonth() ;

Turn string into date - JavaScript

Hey guys I am retrieving a value from an input box and am using that value to turn into a Date for JavaScript the format is Y-m-d h:i:s. It works perfect in Chrome but any other browser says invalid Date
var old = $(".checked-in-time").val();
old = new Date(old);
UPDATE:
Here is what I am doing:
var current = new Date();
var old = $(".checked-in-time").val();
old = Date.parse(old , 'Y-m-d H:i:s');
var newEnd = current - old
minutes = parseInt((newEnd/(1000*60))%60);
var subtractedWaitTime = minutes;
Pretty much getting the time difference based on minutes.
Date.parse accepts a limited number of formats:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
Your format is not one of the ones supported. You can parse it yourself and just pass the arguments directly. One of the forms Date accepts is this, which would be easy enough to pull out from your format:
new Date(year, month[, date[, hour[, minutes[, seconds[, milliseconds]]]]]);
But I would recommend removing the pain of having to worry about cross browser compatibility and parsing things yourself, and use moment instead, where you can parse the date like this
moment(dateStr,'YYYY-M-D H:m:s')
and then if you needed to have it as a Javascript Date object you could just run
moment().toDate();
in the more likely case you just need to display it formatted somewhere, or compare it to other dates, moment offers many functions for formatting, manipulating and comparing dates
http://momentjs.com/docs/#/displaying/as-javascript-date/
Try one of the following formats
MM-dd-yyyy
yyyy/MM/dd
MM/dd/yyyy
MMMM dd, yyyy
MMM dd, yyyy
Could be that some browsers don't support yyyy-mm-dd
You can parse date like this,
var old = $(".checked-in-time").val();
old = Date.parseDate(old , 'yyyy-mm-dd h:i:s');
if the above not working, you can also try Y-m-d H:i:s this format. For me Y/m/d H:i worked fine.
You could try use such format Y-m-dTH:i:s, e.g. 2011-01-01T12:00:00
Or you can use moment library (Javascript Date library)

Comparing date with date in string javascript

I am trying to compare a couple of dates in javascript. First of it, I got froma database. In database it is in date format but after send it in a json file I guess it is just a string.
The second I got it in Date format in javascript. I found this script in javascript:
var todayAEJ = new Date();
var ddAEJ = todayAEJ.getDate();
var mmAEJ = todayAEJ.getMonth()+1; //January is 0!
var yyyyAEJ = todayAEJ.getFullYear();
if(ddAEJ<10){ddAEJ='0'+ddAEJ} if(mmAEJ<10){mmAEJ='0'+mmAEJ} todayAEJ = ddAEJ+'-'+mmAEJ+'-'+yyyyAEJ;
ANd it works like a charm.
The other date is like this: 13-01-2014
I tried to compare like this:
if(todayAEJ > val.date_End)...
But it returns true when today's day is bigger than val.date_End's day. So I cannot use this form when the month is diferent. What can I do in this case?
otherDate = '13-01-2014';
myDate=myDate.split("-");
var newDate=myDate[1]+","+myDate[0]+","+myDate[2];
otherDateTimeStamp = new Date(newDate).getTime();
todayAEJTimeStamp = new Date().getTime();
if(todayAEJTimeStamp > otherDateTimeStammp){
// your code
}
you can even use var newDate=myDate[1]+"/"+myDate[0]+"/"+myDate[2];
Use above code...it will solve your problem!
Iinjoy...
If you can use MM-DD-YYYY format instead of DD-MM-YYYY you can use Date.parse:
var todayAEJTimeStamp = Date.parse(todayAEJ);//Date parse needs `MM-DD-YYYY` format
//if val.date_End is instance of Date
if(todayAEJTimeStamp > val.date_End.getTime()) {
//your code here
}
You have to compare them via microtime
var date = new Date("11/21/1987 16:00:00");
var milliseconds = date.getTime(); // Compare this milliseconds
Apart from timestamp solutions, I would recommend to use date.js in any case you want to play with Date object in JS. Date object has pretty odd behaviour in JS, and this library comes in handy.

Display number of days between 2 datepicker dates?

I am looking to try and calculate the number of days between 2 datepicker fields and display that value in an input field. I have searched a lot of different methods but can't seem to get any to work. I am using boostrap-datepicker.js
I have created a JS fiddle here http://jsfiddle.net/KLpq7/201/ so you can see my effort so far
My JS Is as follows
function days() {
var a = $("#datepicker_start").datepicker('getDate').getTime(),
b = $("#datepicker_end").datepicker('getDate').getTime(),
c = 24*60*60*1000,
diffDays = Math.round(Math.abs((a - b)/(c)));
$("#totaldays").val(diffDays)
}
$('.datepicker')
.datepicker({format: 'DD, dd.mm.yyyy'})
.on('changeDate', function(ev){
$(this).datepicker('hide').blur();
});
In the first part I am trying to achieve this, but it is not working!
Looking for some help...
I have modified your jsfiddle that correctly calculates the differences. One think I noticed is that you use the dd/mm/yyyy format and by default JS wants the dates as mm/dd/yyyy. It is best if you handle it the 'American' way for date difference calculations, but if you must use the 'correct' style of dd/mm/yyyy then I would recommend taking a look at the Globalize library.
function DateDiff(var date1, var date2) {
return date1 - date2;
}
Should work if you pass in two Date objects in Javascript. The result returned will be the number of milliseconds between the two, which can be quite easily converted to days or hours or weeks, etc.

Categories