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

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)

Related

How to get last 2 digits of year from Javascript date [duplicate]

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Why does Date.parse give incorrect results?
(11 answers)
How to get 2 digit year w/ Javascript? [duplicate]
(5 answers)
Closed 3 years ago.
I have string in the following format "30.11.2019". I need to transform it into a Date and get the short year representation (last 2 digits from year) like "19".
The following code doesn't work
var strDate = new Date("30.11.2019");
var shortYear = strDate.getFullYear();
new Date() does not work with a single string argument in that format.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Easiest way is to call it with 3 arguments (year, month, day).
Do note that month is the month index (0 based), so November (11th month) is actually 10th in the format that Date expects.
new Date(2019, 10, 30).getFullYear() % 100;
// returns 19;
If you can't do it this way and you simply must work around the string format mentioned, then you can just do
const dateString = '30.11.2019';
const year = dateString.substring(dateString.length-2);
I'm not entirely sure if you want only short representation of the year or whole date, BUT with short representation of the year on it - if so, then I would suggest using toLocaleDateString method:
new Date(2019, 10, 30).toLocaleDateString('pl', {day: 'numeric', month: 'numeric', year: '2-digit'})
It will return you:
"30.11.19"
or if you want to get the short year date only:
new Date(2019, 10, 30).toLocaleDateString('en', {year: '2-digit'})
it will return you:
"19"
You can get last two digits with the following code:
var strDate = new Date(); // By default Date empty constructor give you Date.now
var shortYear = strDate.getFullYear();
// Add this line
var twoDigitYear = shortYear.toString().substr(-2);
Since the string you're using isn't in a format recognized by Date.parse() (more on that here), you need to manually create that Date object.
For example:
const strDate = '30.11.2019';
let [d,m,y] = strDate.split(/\D/);
const date = new Date(y, --m, d);
console.log(date.getFullYear())
You can then use Date.getFullYear() to get the year and extract the last two digits, as you need.
do not need split string, I think.
using moment
yarn add moment
const moment = require( 'moment' );
const simpleYear = moment( "30.11.2019", "DD.MM.YYYY" ).format( "YY" );
console.log( "simpleYear = " + simpleYear );
var strDate = "30.11.2019";
var lastdigit = strDate.slice(-2);

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.

Get day from Date in JavaScript [duplicate]

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

convert custom date string to date object

How can I convert a string representation of a date to a real javascript date object?
the date has the following format
E MMM dd HH:mm:ss Z yyyy
e.g.
Sat Jun 30 00:00:00 CEST 2012
Thanks in advance
EDIT:
My working solution is based on the accepted answer. To get it work in IE8, you have to replace the month part (e.g. Jun) with the months number (e.g. 5 for June, because January is 0)
Your date string can mostly be parsed as is but CEST isn't a valid time zone in ISO 8601, so you'll have to manually replace it with +0200.
A simple solution thus might be :
var str = "Sat Jun 30 00:00:00 CEST 2012";
str = str.replace(/CEST/, '+0200');
var date = new Date(str);
If you want to support other time zones defined by their names, you'll have to find their possible values and the relevant offset. You can register them in a map :
var replacements = {
"ACDT": "+1030",
"CEST": "+0200",
...
};
for (var key in replacements) str = str.replace(key, replacements[key]);
var date = new Date(str);
This might be a good list of time zone abbreviation.
You can use following code to convert string into datetime:
var sDate = "01/09/2013 01:10:59";
var dateArray = sDate.split('/');
var day = dateArray[1];
// Attention! JavaScript consider months in the range 0 - 11
var month = dateArray[0] - 1;
var year = dateArray[2].split(' ')[0];
var hour = (dateArray[2].split(' ')[1]).split(':')[0];
var minute = (dateArray[2].split(' ')[1]).split(':')[1];
var objDt = new Date(year, month, day, hour, minute);
alert(objDt);

Javascript get date in format [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 3 years ago.
I want to get today's date in the format of mm-dd-yyyy
I am using var currentDate = new Date();
document.write(currentDate);
I can't figure out how to format it.
I saw the examples var currentTime = new Date(YY, mm, dd); and currentTime.format("mm/dd/YY");
Both of which don't work
I finally got a properly formatted date using
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;
document.write(today);'`
This seems very complex for such a simple task.
Is there a better way to get today's date in dd/mm/yyyy?
Unfortunately there is no better way, but instead of reinventing the wheel, you could use a library to deal with parsing and formatting dates: Datejs
<plug class="shameless">
Or, if you find format specifiers ugly and hard to decipher, here's a concise formatting implementation that allows you to use human-readable format specifiers (namely, the Date instance getters themselves):
date.format("{Month:2}-{Date:2}-{FullYear}"); // mm-dd-yyyy
</plug>
var today = new Date();
var strDate = 'Y-m-d'
.replace('Y', today.getFullYear())
.replace('m', today.getMonth()+1)
.replace('d', today.getDate());
Simple answer is no. Thats the only way to do it that I know of.
You can probably wrap into a function that you can reuse many times.
date.js is what you need. For example, snippet below is to convert a date to string as Java style
new Date().toString('M/d/yyyy')
function dateNow(splinter){
var set = new Date();
var getDate = set.getDate().toString();
if (getDate.length == 1){ //example if 1 change to 01
getDate = "0"+getDate;
}
var getMonth = (set.getMonth()+1).toString();
if (getMonth.length == 1){
getMonth = "0"+getMonth;
}
var getYear = set.getFullYear().toString();
var dateNow = getMonth +splinter+ getDate +splinter+ getYear; //today
return dateNow;
}
format this function is mm dd yyyy
and the dividing you can choice and replace if you want... for example
dateNow("/") you will get 12/12/2014
There is nothing built in, but consider using this if you are already using jQuery (and if not, then you should consider that as well!)
http://plugins.jquery.com/project/jquery-dateFormat
(new Date()).format("MM-dd-yyyy")
N.B. month is "MM" not "mm"
function appendZeros(value,digits){
var c= 1;
initValue = value;
for(i=0;i<digits-1;i++){
c = c*10;
if( initValue < c ){
value = '0' + value;
}
}
return value;
}

Categories