Does anyone know how to parse date string in required format dd.mm.yyyy?
See:
Mozilla Core JavaScript Reference: Date object
Mozilla Core JavaScript Reference: String.Split
Code:
var strDate = "03.09.1979";
var dateParts = strDate.split(".");
var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
If you are using jQuery UI, you can format any date with:
<html>
<body>
Your date formated: <span id="date1"></span><br/>
</body>
</html>
var myDate = '30.11.2011';
var parsedDate = $.datepicker.parseDate('dd.mm.yy', myDate);
$('#date1').text($.datepicker.formatDate('M d, yy', parsedDate));
http://jsfiddle.net/mescalito2345/ND2Qg/14/
We use this code to check if the string is a valid date
var dt = new Date(txtDate.value)
if (isNaN(dt))
refs:
http://momentjs.com/docs/#/parsing/string/
If you use moment.js, you can use "string" + "format" mode
moment(String, String);
moment(String, String, String);
moment(String, String, Boolean);
moment(String, String, String, Boolean);
ex:
moment("12-25-1995", "MM-DD-YYYY");
I'v been used following code in IE. (IE8 compatible)
var dString = "2013.2.4";
var myDate = new Date( dString.replace(/(\d+)\.(\d+)\.(\d+)/,"$2/$3/$1") );
alert( "my date:"+ myDate );
ASP.NET developers have the choice of this handy built-in (MS JS must be included in page):
var date = Date.parseLocale('20-Mar-2012', 'dd-MMM-yyyy');
http://msdn.microsoft.com/en-us/library/bb397521%28v=vs.100%29.aspx
Use Date object:
var time = Date.parse('02.02.1999');
document.writeln(time);
Give: 917902800000
This function handles also the invalid 29.2.2001 date.
function parseDate(str) {
var dateParts = str.split(".");
if (dateParts.length != 3)
return null;
var year = dateParts[2];
var month = dateParts[1];
var day = dateParts[0];
if (isNaN(day) || isNaN(month) || isNaN(year))
return null;
var result = new Date(year, (month - 1), day);
if (result == null)
return null;
if (result.getDate() != day)
return null;
if (result.getMonth() != (month - 1))
return null;
if (result.getFullYear() != year)
return null;
return result;
}
you can format date just making this type of the code.In javascript.
// for eg.
var inputdate=document.getElementById("getdate").value);
var datecomp= inputdate.split('.');
Var Date= new Date(datecomp[2], datecomp[1]-1, datecomp[0]);
//new date( Year,Month,Date)
Related
I know this has been asked before but I can't get it to work due to my date format, which I can't change. Any help would be appreciated.
My date is in this format;
4/11/2017 12:30 PM.
If I inspect it in the developer tools it shows it as
4/11/2017 12:30 PM EDIT: Won't show with prepended space here
i.e. with a space in front, not sure if that's relevant.
Does anyone know if it's possible or how to compare it with today's date to see if it's in the past or future?
I've tried tinkering with the following code but can't get it to work because of the time, PM, and forward slashes.
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(d,m,y);
mydate=new Date('13/04/2017');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
If you have dates that are in the same format of something like 13/04/2017, you could split the string based on the slashes and compare the values starting from the right moving left.
By this, I mean when you have your array of three values for each date, you could first compare the year, if that's the same, move on to comparing the month, if that's the same then on to comparing the day.
But if for instance one of the year's is 2018 while the other is 2016, you would immediately know that the 2018 one comes later.
var st = "19/05/2019";
var st2 = "19/05/2019";
function provideLaterDate(date1, date2) {
var splitDateDate1 = date1.split("/").reverse();
var splitDateDate2 = date2.split("/").reverse();
var laterDate = false;
splitDateDate1.forEach(function(val, idx, arr) {
if ( laterDate === false ) {
if ( val > splitDateDate2[idx] ) {
laterDate = splitDateDate1;
} else if ( val < splitDateDate2[idx]) {
laterDate = splitDateDate2;
} else {
laterDate = "Both are the same";
}
}
});
if ( /\//.test(laterDate) ) {
return laterDate.reverse().join("/");
} else {
return laterDate;
}
}
To get rid of the "time pm" part, you could simply do something like:
// Assuming your date has a structure like this: 4/11/2017 12:30 PM.
var newDate = unformattedDate.split(" ")[0];
// This will separate your date string by spaces, and since there are no spaces until after the year in your date, the 0 index will give you the date minus the time and pm portion. Please pardon the not-consistent variable names.
The problem was with the way you were constructing date. Construct date like this var mydate = new Date(2017, 04, 03); and it works.
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(d, m, y);
var mydate = new Date(2017, 04, 03);
console.log(date);
console.log(mydate)
if (date > mydate) {
alert("greater");
}
else {
alert("smaller")
}
You can split the date. Be aware you should contruct your date as follows:
var date = new Date(y,m,d);
Means year first, then month and finally day, as you can see under https://www.w3schools.com/jsref/jsref_obj_date.asp
You can use the following code to perform what you want:
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(y,m,d);
newdate = '13/04/2017'
array = newdate.split('/');
var d1 = array[0]
var m1 = array[1]-1
var y1 = array[2]
mydate = new Date(y1,m1,d1);
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
You can always check the date created is correct by using the date.toString() function. Be aware 0=January for month as you can check under https://www.w3schools.com/jsref/jsref_getmonth.asp. That's why I added the -1 for var m1.
Problem:
It's not working because you are comparing a date with an Invalid date, it will always return false.
Explanation:
And the Invalid date comes from the line new Date('13/04/2017'), because 13 is expected to be a month number and not a day which is an invalid month, because the new Date(stringDate) will be treated as a local Date and not a UTC date by the browser, and it depends on which browser you are using.
You can see in the JavaScript Date Specification that:
parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.
Demo:
So if we change new Date('13/04/2017') to new Date('04/13/2017') the code will work as expected:
var date = new Date();
var mydate = new Date('04/13/2017');
console.log(date);
console.log(mydate)
if (date > mydate) {
alert("greater");
} else {
alert("smaller")
}
if(date.getTime()>mydate.getTime()){
alert("greater");
}
else if (date.getTime()==mydate.getTime){
alert("simmilar");
else {alert("smaller");}
i have textbox when user enter data with MM/dd/yyyy format then i need to parse that data and convert it to date. i used momentjs but my code not working. here is my code snippet.
var otherProp = $('#' + param.otherproperty);
var StartDate = new date(moment(otherProp.val(), 'MM/dd/yyyy'));
specially this line is not working var StartDate = new date(moment(otherProp.val(), 'MM/dd/yyyy')); where i made the mistake ?
thanks
UPDATE
my full code as follows
$.validator.addMethod("isgreater", function (value, element, param) {
var otherProp = $('#' + param.otherproperty);
var StartDate = new Date(moment(otherProp.val(), 'MM/DD/YYYY'));
var Enddate = new Date(value);
if (StartDate != '')
{
return Enddate >= StartDate;
}
return false;
});
convert all of the MM/dd/yyyy to uppercase MM/DD/YYYY
so this should work
var otherProp = $('#' + param.otherproperty);
var StartDate = new Date(moment(otherProp.val(), 'MM/DD/YYYY'));
I have a form with a simple input type. I'm trying to define a function to check if the date is no more than 6 months older compared to date provided by the input type.
I know i have to convert the String provided by the input in a Date object to make this comparison and then work on get methods of Date object, but i can't figure out how to do this.
Current code:
$scope.compareDates = function(d1) {
d1 = new Date(d1); //convert String into date Object
var d = new Date(); // today date
d.setYear(d.getFullYear());
d.setMonth(d.getMonth() - 6);
if(d1 > d ) {
console.log("ok");
} else {
console.log("error");
}
}
EDIT:
I'm sorry, i forgot to add my input. Here it is:
<input class="form-control" type="text" placeholder="gg/mm/aaaa" ng-model="sStartDate" ng-change="change()">
Angular Controller:
$scope.sStartDate = '';
$scope.change = function(){
var startDt = $scope.sStartDate;
$scope.compareDates(startDt);
}
If I am reading your code correctly, your date format is days/month/year which is not valid format. You need to swap the month and days.
var parts = d1.split(),
dateStr = parts[1] + "/" + parts[0] + "/" parts[2],
d1 = new Date(d1),
d = new Date();
d.setMonth(d.getMonth() - 6);
if(d1 > d ) {
console.log("ok");
} else {
console.log("error");
}
What's about using d.getTime()?
$scope.compareDates = function(d1){
d1 = new Date(d1); //convert String into date Object
var d = new Date(); // today date
d.setMonth(d.getMonth() - 6);
if(d1.getTime() > d.getTime() ) {
console.log("ok");
} else {
console.log("error");
}
}
Regards.
I used momentjs for this in our app. It makes this process very easy and smooth.
// is6MonthsOld will be a boolean value
var is6MonthsOld = moment(d1).isBefore(moment().subtract(6, 'months'));
If you are comparing dates and not time, make sure to reset time in your date object using d1.setHours(0,0,0,0).
When you do new Date(), output is a datetime object, but when you do new Date(2015,6,19), only date is assigned and time is set to 00:00:00.
Following code depicts the same:
function compareDates(d1,d2){
return +d2 > +d1;
}
function compareDatesWithHoursReset(d1,d2){
d1.setHours(0,0,0,0);
d2.setHours(0,0,0,0);
return +d2 > +d1;
}
function main(){
var d1 = new Date();
var d2 = new Date(2015, 6, 19);
d1.setMonth(d1.getMonth() - 6)
console.log(d1);
console.log(d2);
console.log(compareDates(d2,d1))
console.log(compareDatesWithHoursReset(d2,d1))
}
main();
In my ajax success I am getting result.Date as "/Date(-2208967200000)/". I need to check with the following date and proceed..
How to convert the "/Date(-2208967200000)/" to "01-01-1900" for below if condition?
if (result.Date != "01-01-1900") {
....
}
You can convert result.Date into you comparison date format, same as below example
var dateString = "\/Date(-2208967200000)\/".substr(6);
var currentTime = new Date(parseInt(dateString ));
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var date = day + "/" + month + "/" + year;
After doing this.. you can compare it with other date..
Reference
var jsonDate = "/Date(-2208967200000)/";
var date = new Date(parseInt(jsonDate.substr(6)));
alert(date);
The substr function takes out the "/Date(" part, and the parseInt function gets the integer and ignores the ")/" at the end. The resulting number is passed into the Date constructor.
jQuery dateFormat is a separate plugin. You need to load that explicitly using a tag.
You could use a regex to get the value between the brackets and then pass that to the Date():
var input = "/Date(-2208967200000)/";
var matches = /\(([^)]+)\)/.exec(input);
var date = new Date(parseInt(matches[1], 10));
Example fiddle
I'm using bootstrap plugin as datepicker, I wrote a function to check whether it's today or not using pure js..
nothing happen, I wonder why.. the datepicker value is in format like dd/mm/yyyy
var datepicker = $('#datepicker').val();
checkToday(datepicker);
function checkToday(datepicker){
datepickerDay = datepicker.slice(0, datepicker.indexOf('/'));
var d = new Date();
var dToday = d.getDate() ;
dToday.toString();
if(datepickerDay == dToday){
return "Today"
alert('Today');
}
else{
return datepicker;
alert(datepicker);
}
}
Don't use parseInt Also you can't put anything after the return
var datepicker = $('#datepicker').val();
function checkToday(datepicker) {
datepickerDay = datepicker.slice(0, datepicker.indexOf('/'));
var d = new Date();
var dToday = d.getDate();
dToday.toString();
if (datepickerDay == dToday) {
return "Today";
} else {
return datepicker;
}
}
alert(checkToday(datepicker));
WORKING DEMO
You van convert both the dates in dates format then compare by date, month and year.
try this
function checkToday(datepicker){
var datepickerDay = new Date(datepicker); //creating date object from string 'mm/dd/yyyy'
var d = new Date(); // date object
// now lets comapare date, Month and year to get correct result
if(d.getDate()==datepicker.getDate() && d.getMonth()==datepicker.getMonth() && d.getYear()==datepicker.getYear()){
return "Today"
alert('Today');
}
else{
return datepicker;
alert(datepicker);
}
}
Hope this helps...