Get day from Date in JavaScript [duplicate] - javascript

This question already has answers here:
Convert dd-mm-yyyy string to date
(15 answers)
Closed 9 years ago.
I want to get day from date. Suppose my date is 03-08-2013 it is in d-mm-yyyy format so I just want to get dand that is 03 from above date so I try this code but it does not work
Note
I want to do it without including any js
var date = '08-03-2013';
var d = new Date(date);
alert(d.getDate());
// 2nd way
alert(date.getDate());
it alert NaN. What is missing in this code?
here is jsfiddel Link Jsfiddle Link
UPDATE

Date parsing in JS (and many languages, for that matter) is problematic because when the input is a date string, it's fairly ambiguous what piece of data is what. For example, using your date (August 3, 2013) it could be represented as
03-08-2013 (dd-mm-yyyy)
08-03-2013 (mm-dd-yyyy)
However, given just the date string, there's no way to tell if the date is actually August 3, 2013 or March 8, 2013.
You should pass your date values independently to guarantee the date is correctly parsed:
var
str = '08-03-2013',
parts = str.split('-'),
year = parseInt(parts[2], 10),
month = parseInt(parts[1], 10) - 1, // NB: month is zero-based!
day = parseInt(parts[0], 10),
date = new Date(year, month, day);
alert(date.getDate()); // yields 3
MDN documentation for Date

You can't know the regional settings of your visitors.
If you know the format of the string is always d-mm-yyyy then just parse the value yourself:
function GetDay(rawValue) {
var parts = rawValue.split("-");
if (parts.length === 3) {
var day = parseInt(parts[0], 10);
if (!isNaN(day))
return day;
}
alert("invalid date format");
return null;
}
Live test case.

Use moment.js. It's parsing ability is much more flexible than the Date class.
var m = moment('03-08-2013','DD-MM-YYYY');
var dayOfMonth = m.date();

Use this it that which you want..
var date = '08-03-2013';
date=date.replace(/([0-9]{2})\-([0-9]{2})\-([0-9]{4})/g, '$3-$2-$1');
var d = new Date(date);
alert(d.getDate());
Thanks

Related

getMonth() in Javascript from format dd/mm/yyyy [duplicate]

This question already has answers here:
Convert dd-mm-yyyy string to date
(15 answers)
Closed 3 years ago.
I have a date in format dd/mm/yyyy and when I try to use getMonth() I get the dd field.
For example if I have "01/12/2019" it will take 01 as month instead of 12. Is there a way to get the month from this format?
This is my code:
var beginDate = document.getElementById("beginDate").value;
var month = new Date(beginDate).getMonth();
inside beginDate there's "01/10/2019" (October 1st 2019)
It's better to use any external libraries like momentjs or datejs. Try this it may solve your problem now.
const date = "01/12/2019";
const split = date.split('/');
console.log('day', split[0])
console.log('month', split[1])
console.log('year', split[2])
var date = moment('01/12/2019', 'DD/MM/YYYY');
console.log(date.month()+1);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
You can use something like Moment.js
const beginDate = "22/05/2019"
const date = moment(beginDate, 'DD/MM/YYYY');
const month = date.format('M');
console.log(month)
//05
Make it easy.
You don't need external libraries:
var beginDate = "01/10/2019";
var timeZone = 'your time zone'; //en-GB etc...
var month = new Date(beginDate).toLocaleString(timeZone , {month: "2-digit"}); //month = 10
I don't think that you need some external library to do this task. You should use javascript date object to get it done easily, getMonth() returns month indexed from 0 to 11. Prefer javascript always instead of unnecessarily importing external js files for libraries
var beginDate = document.getElementById("beginDate").value;
let reg = /(\d\d)\/(\d\d)\/(\d+)/gi;
const[date,mon,year] = reg.exec(beginDate).splice(1);
month = new Date(year,mon-1,date).getMonth(); // months are indexed from 0 to 11 for jan to dec
console.log(month); // 0 for jan and 11 for dec
Month in javascript is 0 indexed that mean 0 represent January, So you need to add 1 to get the month correctly
function getMonth(dt) {
let splitDt = dt.split('/');
return new Date(`${splitDt[2]}-${splitDt[1]}-${splitDt[0]}`).getMonth() + 1;
}
console.log(getMonth("01/10/2019"))
1st oct
You can get months using getMonth() as shown below, But here 0=January, 1=February etc.
var date = "05/12/2019"
var d = new Date(date);
var n = d.getMonth();
console.log(n)

Reading the date from textbox as a string and converting it into as Date

I am reading the date from textbox by using javascript and trying to convert it as Date object.But my problem is date is converting as month and month is converting as date when converting the string to date.
Example:
03/12/2014 the value in the textbox
Actual Output:
03 as March,
12 as date (Its wrong)
Expected Output:
03 as date
12 as December (I am expecting)
While converting this string to date by using following snippet
var startTime = document.getElementById("meeting:startTime");
date.js
var stringToDate_startTime=new Date(Date.parse(startTime.value,"dd/mm/yy"));
moment.js
var date1=moment(startTime.value).format('DD-MM-YYYY');
In the above even i have used date.js and moment.js files also.But those also did not solve my problem.Please can anyone help me out to get rid out of this.
Try ...
var from = startTime.value.split("/");
var newDate = newDate(from[2], from[1] - 1, from[0]);
... assuming time included ...
var date_only = startTime.value.split("");
var from = date_only[0].split("/");
var newDate = newDate(from[2], from[1] - 1, from[0]);
I am not aware of an implementation of the Date.parse() method that accepts two arguments. You can view the Mozilla Date.parse() method description here Date.parse() - JavaScript | MDN.
It might be worth looking at the question/answer of this question for some more information: Why does Date.parse give incorrect results?
The next best option would be to split the date using String.split() and to rearrange the date parts
var dateStr = '03/12/2014 23:05';
var newDateStr = null;
var dateParts = dateStr.split('/');
if (dateParts.length == 3) {
var day = dateParts[0];
var month = dateParts[1];
var yearAndTime = dateParts[2];
// Rearrange the month and day and rejoin the date "12/03/2014 23:05"
newDateStr = [ month, day, yearAndTime].join('/');
} else {
throw new Error('Date not in the expected format.');
}
var date = new Date(newDateStr); // JS Engine will parse the string automagically
alert(date);
This isn't the most elegant solution, but hopefully that helps.

Parsing Date with javascript in FireFox

I have strange date format like this dMMMyyyy (for example 2Dec2013).
I'm trying to create Date object in my javascript code:
var value = "2Apr2014";
var date = new Date(value);
alert(date.getTime());
example
in Google Chrome this code works fine but in FireFox it returns Null
Can anyone suggest something to solve this problem
Thanks.
How about just parsing it into the values new Date accepts, that way it works everywhere
var value = "02Apr2014";
var m = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var month = value.replace(/\d/g,''),
parts = value.split(month),
day = parseInt(parts.shift(), 10),
year = parseInt(parts.pop(), 10);
var date = new Date(year, m.indexOf(month), day);
FIDDLE
This fiddle works in both firefox and chrome
var value = "02 Apr 2014";
var date = new Date(value);
alert(date.getTime())
Check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
I would suggest using something like jQuery datepicker to parse your dates.
I haven't tested it but it seems you'd need something like:
var currentDate = $.datepicker.parseDate( "dMyy", "2Apr2014" );
jsFiddle
Just be aware of:
d - day of month (no leading zero)
dd - day of month (two digit)
M - month name short
y - year (two digit)
yy - year (four digit)
However if for some reason you really wanted to do it yourself, then you could check out this link: http://jibbering.com/faq/#parseDate
It has some interesting examples on parsing dates.
Whilst not exactly what you want, the Extended ISO 8601 local Date format YYYY-MM-DD example could be a good indication of where to start:
/**Parses string formatted as YYYY-MM-DD to a Date object.
* If the supplied string does not match the format, an
* invalid Date (value NaN) is returned.
* #param {string} dateStringInRange format YYYY-MM-DD, with year in
* range of 0000-9999, inclusive.
* #return {Date} Date object representing the string.
*/
function parseISO8601(dateStringInRange) {
var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
date = new Date(NaN), month,
parts = isoExp.exec(dateStringInRange);
if(parts) {
month = +parts[2];
date.setFullYear(parts[1], month - 1, parts[3]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
}
}
return date;
}
You can use following JavaScript Library for uniform date parser across browser.
It has documentation
JSFIDDLE
code:
var value = "2Apr2014";
var date =new Date(dateFormat(value));
alert(date.getTime());

Comparing dates Java Script

I have the following scenario that I am strugling to code.
I have a valuation date that is a string that is chosen by a user from a calander popup. What I need to do is take that date and pass it into a function that works outs a second date depending on the value of that date. If the first date is more than 7 days from the first day of the month use the first day of the month else use the last day of the month. This needs to happen in client side as this date need to be displayed after they have chosen the first date.
SO far I have the below:
Function CompareDate()
{ var date1 = document.getElementById("textbox1");
var x = new date();
var year = x.getYear();
var day = x.getDay();
var thisMonthFirstDay = new Date(year, month,1)
var thisMonthLastDate = ....
var 1day = 1000*60*60*24
var date1_ms = recdate
var date2ms = thisMonthFirstDay.gettime()
if(Math.round(difference_ms/1day) > 7
{var textbox = document,getelementbyid("textbox2");
textbox.value = texbox.value + thisMonthLastDate
}
else
{
textbox.value = texbox.value + thisMonthFirstDay }
}
Any examples of how this can be done would be greatly appeciated.
Cheers
getDate() will give you the day of month (e.g. 18), so if (getDate() <= 7) { outputDate = 1; } If you're having a problem getting the last day of each month for the else statement, I generally use a 12 capacity array with hard-coded values, adding 1 to February if (year % 4 == 0).
I have managed to resolve this after a finding the parseDate() function on a fiddler site. That allowed me to convert the date from this format (31 Jan 2013) to a date and then I could just use the getDay(function) to see if the day was > 7. From there it was easy!
Thanks for above suggestions.

How to create a date object from string in javascript [duplicate]

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Closed 5 years ago.
Having this string 30/11/2011. I want to convert it to date object.
Do I need to use :
Date d = new Date(2011,11,30); /* months 1..12? */
or
Date d = new Date(2011,10,30); /* months 0..11? */
?
var d = new Date(2011,10,30);
as months are indexed from 0 in js.
You definitely want to use the second expression since months in JS are enumerated from 0.
Also you may use Date.parse method, but it uses different date format:
var timestamp = Date.parse("11/30/2011");
var dateObject = new Date(timestamp);
The syntax is as follows:
new Date(year, month [, day, hour, minute, second, millisecond ])
so
Date d = new Date(2011,10,30);
is correct; day, hour, minute, second, millisecond are optional.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
There are multiple methods of creating date as discussed above. I would not repeat same stuff. Here is small method to convert String to Date in Java Script if that is what you are looking for,
function compareDate(str1){
// str1 format should be dd/mm/yyyy. Separator can be anything e.g. / or -. It wont effect
var dt1 = parseInt(str1.substring(0,2));
var mon1 = parseInt(str1.substring(3,5));
var yr1 = parseInt(str1.substring(6,10));
var date1 = new Date(yr1, mon1-1, dt1);
return date1;
}
Very simple:
var dt=new Date("2011/11/30");
Date should be in ISO format yyyy/MM/dd.
First extract the string like this
var dateString = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
Then,
var d = new Date( dateString[3], dateString[2]-1, dateString[1] );
Always, for any issue regarding the JavaScript spec in practical, I will highly recommend the Mozilla Developer Network, and their JavaScript reference.
As it states in the topic of the Date object about the argument variant you use:
new Date(year, month, day [, hour, minute, second, millisecond ])
And about the months parameter:
month Integer value representing the month, beginning with 0 for January to 11 for December.
Clearly, then, you should use the month number 10 for November.
P.S.: The reason why I recommend the MDN is the correctness, good explanation of things, examples, and browser compatibility chart.
I can't believe javascript isn't more consistent with parsing dates. And I hear the default when there is no timezone is gonna change from UTC to local -- hope the web is prepared ;)
I prefer to let Javascript do the heavy lifting when it comes to parsing dates. However it would be nice to handle the local timezone issue fairly transparently. With both of these things in mind, here is a function to do it with the current status quo -- and when Javascript changes it will still work but then can be removed (with a little time for people to catch up with older browsers/nodejs of course).
function strToDate(dateStr)
{
var dateTry = new Date(dateStr);
if (!dateTry.getTime())
{
throw new Exception("Bad Date! dateStr: " + dateStr);
}
var tz = dateStr.trim().match(/(Z)|([+-](\d{2})\:?(\d{2}))$/);
if (!tz)
{
var newTzOffset = dateTry.getTimezoneOffset() / 60;
var newSignStr = (newTzOffset >= 0) ? '-' : '+';
var newTz = newSignStr + ('0' + Math.abs(newTzOffset)).slice(-2) + ':00';
dateStr = dateStr.trim() + newTz;
dateTry = new Date(dateStr);
if (!dateTry.getTime())
{
throw new Exception("Bad Date! dateStr: " + dateStr);
}
}
return dateTry;
}
We need a date object regardless; so createone. If there is a timezone, we are done. Otherwise, create a local timezone string using the +hh:mm format (more accepted than +hhmm).

Categories