I have a date which is provided as a string such as 09/12/2012.
If the string is today, I wish to display "Today", else I wish to display 09/12/2012.
The problem with my approach shown below is that a month like 09 gets parsed to 0 and not 9.
What is the best way to do this? Thank you
var currentDate = new Date();
dateText='09/12/2012';
var a=dateText.split('/');// mdY
$("#date").text(((parseInt(a[0])-1==currentDate.getMonth()&&parseInt(a[1])==currentDate.getDate()&&parseInt(a[2])==currentDate.getFullYear())?'Today':dateText));
Pass a second argument to parseInt() - specifically, 10.
$("#date").text(((parseInt(a[0], 10)-1==currentDate.getMonth()&&parseInt(a[1], 10)==currentDate.getDate()&&parseInt(a[2], 10)==currentDate.getFullYear())?'Today':dateText));
The second argument tells the function the base to use for interpreting the expression. If you don't pass that explicitly, it uses the old C conventions, which will lead to numbers starting with a zero to be interpreted as base 8 constants. That causes problems for 08 and 09.
Here's a fiddle: http://jsfiddle.net/pfHA7/1/
function today()
{
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} var today = mm+'/'+dd+'/'+yyyy;
return today;
}
var dateText = '09/12/2012';
$("#date").text( today() == dateText ? 'Today' : dateText );
Related
I am facing one issue. I need to compare the given date with the today date using Javascript. I am explaining my code below.
function getCurrentDate(){
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
if(dd<10)
{
dd='0'+dd;
}
if(mm<10)
{
mm='0'+mm;
}
today = dd+'-'+mm+'-'+yyyy;
return today;
}
var givendate=new Date('19-01-2018');
var todaydate=$scope.getCurrentDate();
if (givendate >= todaydate) {
console.log('bool',true);
}else{
console.log('bool',false);
}
Here I should get the result true but here I am getting the console message as false. Please help me to resolve this issue.
The below code works. Like the others said, you need to ensure that you are specifying the date in the proper format as expected by the Date constructor.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<p id="today"></p>
<p id="text"></p>
<script>
today = new Date();
jan19 = new Date('2018-01-19')
document.getElementById("demo").innerHTML = jan19;
document.getElementById("today").innerHTML = today;
if (today < jan19) {
document.getElementById("text").innerHTML = 'true';
}
else {
document.getElementById("text").innerHTML = 'false';
}
</script>
</body>
</html>
As you said in the comments givendate is "Invalid Date" - that's why you have false.
So, before parsing a date, check how to detect invalid date
new Datetries to parse following ISO 8601 format. Quoting:
The formats are as follows. Exactly the components shown here must be present,
with exactly this punctuation. Note that the "T" appears
literally in the string, to indicate the beginning of the time
element, as specified in ISO 8601.
Year:
YYYY (eg 1997)
Year and month:
YYYY-MM (eg 1997-07)
Complete date:
YYYY-MM-DD (eg 1997-07-16)
Complete date plus hours and minutes:
YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
Complete date plus hours, minutes and seconds:
YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
Complete date plus hours, minutes, seconds and a decimal fraction of a
second
YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)
where:
YYYY = four-digit year
MM = two-digit month (01=January, etc.)
DD = two-digit day of month (01 through 31)
hh = two digits of hour (00 through 23) (am/pm NOT allowed)
mm = two digits of minute (00 through 59)
ss = two digits of second (00 through 59)
s = one or more digits representing a decimal fraction of a second
TZD = time zone designator (Z or +hh:mm or -hh:mm)
Make sure you pass a correctly formatted date when constructing a date object. All the details you need on the subject can be found in JS MDN, on the Date.parse topic
If you want to continue with your current date format(dd-MM-yyyy), then you may need to split the string by - and rearrange accordingly to make a valid date.
JS Code
function getCurrentDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10)
dd = '0' + dd;
if (mm < 10)
mm = '0' + mm;
today = dd + '-' + mm + '-' + yyyy;
return today;
}
var todayDate = getCurrentDate().toString();
var givenDate = '19-01-2018';
var todayDateArray = todayDate.split('-');
var givenDateArray = givenDate.split('-');
todayDate = new Date(todayDateArray[2] + '-'
+ todayDateArray[1] + '-'
+ todayDateArray[0]);
givenDate = new Date(givenDateArray[2] + '-'
+ givenDateArray[1] + '-'
+ givenDateArray[0]);
if(givenDate >= todayDate)
console.log('bool', true);
else
console.log('bool', false);
This works for me. If you don't want a custom formatted date then you can use this.
function getCurrentDate(){
var today = new Date();
return today;
}
var givendate=new Date("2018-01-19");
var todaydate= getCurrentDate();
console.log(givendate);
console.log(todaydate);
if (givendate >= todaydate) {
console.log('bool',true);
}else{
console.log('bool',false);
}
I have a function in my controller that will take two parameters , these parameters are beeing sent by a javascript function.
function seance(id)
{
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd;
}
if(mm<10) {
mm='0'+mm;
}
var today = mm+'/'+dd+'/'+yyyy;
window.location.href = "<?php echo site_url('index.php/seance/liste_seance/')?>/" + id + "/" + today;
}
but only the first variable is sent correctly!
How can I send these two parameters?
It would be better if you show us your controller.
But I see some problems in your JS.
You are usint var today in your js two times. Remove var on the line 16.
Your site url will be in this format: http://example.com/index.php/seance/liste_seance//id/04/27/2017. Remove slash / after liste_seance. And you should change your date format, because in your controller you are getting 4 parameters: id, 04, 27 and 2017.
I have a date at a string - dtStr
var dtStr = "Thu May 28 02:13:16 BDT 2015";
I want to get a date like - MM DD YYYY HH mm format from the dtStr. For getting this I am trying to convert the dtStr to a Date and then try to use date format like this -
var dtStr = "Thu May 28 02:13:16 BDT 2015";
today = new Date(dtStr);
alert( today.toLocalDateFormat("MM DD YYYY HH mm") );
But it didn't work for me. Can any one help me for - converting dtStr to a date with format MM DD YYYY HH mm ?
Thanks in advance.
Unfortunately, the string you're trying to parse won't be accepted by Date.parse(), the method that will parse the string when you're creating it. If the string will always be in that format, you could do some string manipulation and rearrange it to the RFC2822/IETF format, which Date() can handle.
// this creates a proper Date object
new Date("Thu, May 28 2015 02:13:16 +0600");
Alternatively, you could create a new Date object with one of the other constructors, by splitting/parsing the string yourself, and inserting them in the correct places in the constructor.
At this point, you'll have a Date object, but you still need to get the values from it - the only built in method that can do something like what you're trying to do is toLocaleFormat(), which isn't standard track (it's not supported in my version of Chrome, for example). Thus, you would need to get the values independently, and concatenate them together.
At this point, it's probably easier to just do straight up parsing of the string, and skip the Date object altogether, or use a library like datejs, which provides support for formatting output strings.
You may try to use the following method -
function formatReview(date){
/*****************************************************************
* The method parameter 'date' is in the following format -
* "Thu May 28 02:13:16 BDT 2015"
* Javascript 'new Date()' has not suitable constructor to
* support this format. The parameter 'date' need to
* convert to fee the Date() constructor.
*******************************************************************/
var monthSymbols = "JanFebMarAprMayJunJulAugSepOctNovDec";
var elements = date.split(" ");
var day = elements[0];
var monthName = elements[1];
var monthIndex = monthSymbols.indexOf(monthName)/3 +1;
var date = elements[2];
var year = elements[5];
var timestamp = elements[3];
var timestampElements = timestamp.split(":");
var hour = timestampElements[0];
var minutes = timestampElements[1];
var dateString = monthIndex +"-"+ date +"-"+ year +" "+ hour +":"+ minutes;
return dateString;
}
Try this
var todayDate=new Date("Thu May 29 2014 13:50:00");
var format ="AM";
var hour=todayDate.getHours();
var min=todayDate.getMinutes();
if(hour>11){format="PM";}
if (hour > 12) { hour = hour - 12; }
if (hour == 0) { hour = 12; }
if (min < 10){min = "0" + min;}
document.write(todayDate.getMonth()+1 + " / " + todayDate.getDate() + " / " + todayDate.getFullYear()+" "+hour+":"+min+" ");
fiddle: http://jsfiddle.net/e0ejguju/
Sorry, but what is the fastest way to display the current date?
2014-01-18 Saturday 12:30
with this function or how do it the right way?
var d=new Date();
var t=d.getTime();
Try
var d = new Date();
var dd = d.getDate();
var mm = d.getMonth()+1; //January is 0!
var yy = d.getFullYear();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
var day=weekday[d.getDay()];
var h = d.getHours();
var m = d.getMinutes();
alert(yy+"-"+mm+"-"+dd+" "+day+" "+h+":"+m)
DEMO
var d = new Date();
alert(d.toString());
If you don't mind the format, you can do it in one line:
''+new Date()
You only need to use a Date object as a string, in order to implicitly call its .toString() method, which
returns a String value. The contents of the String are
implementation-dependent, but are intended to represent the Date in
the current time zone in a convenient, human-readable form.
new Date().toGMTString()
It's something similar to what you are looking for
If you want complicate the output you can get element by element and format yourself the date (or you can use Globalize.js)
I know a way to do in java:
Calendar c5 = Calendar.getInstance();
c5.add(Calendar.MONTH, -6);
c5.getTime(); //It will give YYYYMMDD format three months ago.
Is there a way to do this in javascript. I know that I can use
Date d = new Date(); parse it and do some code to get the format.
But now I dont want to do parsing and getting three month ago date.
var dt = new Date('13 June 2013');
dt.setMonth(dt.getMonth()-1)
Then you can use this piece of code from this answer to convert it to YYYYMMDD
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + (mm[1]?mm:"0"+mm[0]) + (dd[1]?dd:"0"+dd[0]); // padding
};
d = new Date();
d.yyyymmdd();
Something to be careful of. If you're at Mar 31 and subtract a month, what happens? You can't get Feb 31! See this answer for more details.