Format Date from String in javascript - javascript

I have a string that has a date in it and I wan't to be able to convert it.
var startDate = "March-09-2010";
var convertedStartDate = new Date(startDate);
var month = convertedStartDate.getMonth() + 1
var day = convertedStartDate.getDay();
var year = convertedStartDate.getFullYear();
var shortStartDate = month + "-" + day + "-" + year;
alert(shortStartDate);
I want it so it converts March-09-2010 to 09-03-10 (DD-MM-YY)
Anyone know what I am doing wrong?

var startDate = "March-09-2010";
var convertedStartDate = new Date(startDate.replace(/-/g, "/")); // replace hyphen with slash
var month = convertedStartDate.getMonth() + 1
var date = convertedStartDate.getDate();
var year = convertedStartDate.getFullYear();
var shortStartDate = date + "-" + month + "-" + year;
alert(shortStartDate);
demo: http://jsfiddle.net/BjnBW/

Try this:
var dt=Date.parse(Yourstring);
formatDate('DD-MM-YY',dt);
Please check this Date.parse

Check your syntax changed your code a little, modify it according to it then ---
var startDate = "March/09/2010";
var convertedStartDate = new Date(startDate);
var month = convertedStartDate.getMonth() + 1
var day = convertedStartDate.getDate();
var year = convertedStartDate.getFullYear();
var shortStartDate = day+ "-" + month+ "-" + year;
alert(shortStartDate);

your date string is not in the correct format. for correct formats, please see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
try this or jsfiddle
var startDate = "March-09-2010";
var tmp = startDate.split('-');
tmp.splice(1, 0, ',');
var convertedStartDate = new Date(tmp.join(' '));
var month = convertedStartDate.getMonth() + 1
var day = convertedStartDate.getDate();
var year = convertedStartDate.getFullYear();
var shortStartDate = ('0' + day).slice(-2) + "-" + ('0' + month).slice(-2) + "-" + year;
alert(shortStartDate);

var shortStartDate =
Globalize.format(Globalize.parseDate(startDate, 'MMMM-dd-yyyy'), 'dd-MM-yy');
Use some library to do the conversion, because the built-in Date.parse() is implementation-dependent. It depends on the system locale what formats it accepts.
The code above uses Globalize.js, which can handle a large number of date formats, including formats with month names in different languages (the default being English).

You'll need to convert 'March' to a number. One way is to use this Array extension to be able to retrieve a month number from a month name:
Array.prototype.enum = function(){
var obj = {};
for (var i=0; i<this.length; (i+=1)) {
obj[this[i]] = i;
}
this.enum = obj;
return this;
};
Now, create an Array with month names
var months = ('January,February,March,April,May,June,July,'+
'August,September,October,November,December').split(',')
.enum();
Now you rewrite your date:
var startDate = "March-09-2010".split(/\-/),
month = months.enum[startDate[0]]+1;
startDate = [startDate[1],
month < 10 ? '0'+month : month,
startDate[2]].join('-');
//=> startDate now is: '09-03-2010'

Use getDateFromFormat() to convert string to date in javascript.
Check this link for more help: http://www.mattkruse.com/javascript/date/

Related

Javascript n months after today

I am trying to get the day 90 days after today. This is my code:
var today = new Date();
var threeMonthsFromToday = new Date(today.setDate(today.getDate() + 90));
When I print threeMonthsFromToday, I get the correct date: 2017-04-24T15:17:42.641Z. However, when I try to reformat the date to be in the form dd/mm/yyyy using this code:
var day = ('0' + threeMonthsFromToday.getDate()).slice(-2);
var month = ('0' + threeMonthsFromToday.getMonth() + 1).slice(-2);
var year = threeMonthsFromToday.getFullYear();
var date = day + '/' + month + '/' + year;
I get a completely different and invalid date: 24/31/2017.
I have been debugging this for hours and still can't seem to figure what I am doing wrong.
Well, '0' + threeMonthsFromToday.getMonth() give you a string : "03" then you add 1 converted to string giving you "031" for month before slice.
Use this :
var month = ('0' + (threeMonthsFromToday.getMonth() + 1)).slice(-2);
You are missing the basic BODMAS rule here please modify your code as follows
var today = new Date();
var threeMonthsFromToday = new Date(today.setDate(today.getDate() + 90));
var day = ('0' + threeMonthsFromToday.getDate()).slice(-2);
var month = ('0' + (threeMonthsFromToday.getMonth() + 1)).slice(-2);
var year = threeMonthsFromToday.getFullYear();
var date = day + '/' + month + '/' + year;
the operations are performed from left to right, so month is getting converted to string before being added to a number. Including a bracket will first perform operation inside bracket and then make it a string
Can you use toLocaleString?
threeMonthsFromToday.toLocaleDateString('en-GB')
Below does the trick for you ...
getMonth() +1 before adding the "0" to it so that you get an arithematic +1
var today = new Date();
var threeMonthsFromToday = new Date(today.setDate(today.getDate() + 90));
var day = ('0' + threeMonthsFromToday.getDate()).slice(-2);
var month = ('0' + (threeMonthsFromToday.getMonth()+1)).slice(-2);
var year = threeMonthsFromToday.getFullYear();
var date = day + '/' + month + '/' + year;
console.log(date);
This should work.
var day = threeMonthsFromToday.getDate()
if(day < 10){
day = '0' + day
}
var month = threeMonthsFromToday.getMonth()+1
if(month<10){
month = '0' + month
}
var year = threeMonthsFromToday.getFullYear()
var date = day + '/' + month + '/' + year
Use Simple toLocaleDateString method
The toLocaleDateString() method returns a string with a language sensitive representation of the date portion of this date.
var today = new Date();
var threeMonthsFromToday = new Date(today.setDate(today.getDate() + 90));
var date = threeMonthsFromToday.toLocaleDateString();
console.log(date);
//result in console : "24/04/2017"
Try it out on your console.

How to convert Date format in Javascript

I want to change date format sequence from yy-mm-dd to dd-mm-yy
How can I do it in Javascript ?
I have tried
var now = new Date();
now.format("mm-dd-yy");
But its not working for me
Here is a clear and simple approach
var now = new Date();
var dd = now.getDate(); //returns date
var mm = now.getMonth()+ 1; //returns month and you need to add1 because it is array
var yy = now.getFullYear(); //returns full year
var st = dd + '-' + mm + "-" + yy; //format as string
var dateFormatted = (now.getMonth()+1)+"-"+now.getDate()+"-"+now.getFullYear();
You can use the below mentioned function to format Date
utilities.FormatDate(new Date(),"GMT", "dd/MM/yyyy")
function dateformat(date)
{
var yourdate = new Date(date);
yourdate = yourdate.getDate() + '-' + yourdate.getMonth() +1 + "-" +yourdate.getFullYear();
}
use - or / as you like

How to format dates in javascript

I pick this date from a textbox and i would like to format to this format: yyyy-MM-dd
So from dd/MM/yyyy to yyyy-MM-dd
var startDate = document.getElementById('ctl00_PlaceHolderMain_ctl00_Date').value;
var s = new Date(startDate);
alert(startDate); //which prints out 7/03/2012
//when i use the below to try and format it to : yyyy-MM-dd which is what i want
var scurr_date = s.getDate();
var scurr_month = s.getMonth();
scurr_month++;
var scurr_year = s.getFullYear();
For some reason i get:
var fstartdate = scurr_year + "-" + scurr_month + "-" + scurr_date;
//Output:2012-7-3
instead of : 2012-3-7
also fi i pick a date like 31/12/2011
i get : 2013-7-12
Any ideas what to do.I kind of notice if i use US like 03/07/2012 it kind os works ok.
Thank in advance
You said you want to convert from "dd/MM/yyyy to yyyy-MM-dd". JavaScript's Date constructor will always take the first two digits as a month.
Some regex might help you here:
function fix_date (str) {
var re = /(\d{1,2})\/(\d{1,2})\/(\d{4})/;
str = str.replace(re, function (p1, p2, p3, p4) {
return p4 + '/' + p3 + '/' + p2;
});
return str;
}
var start_date = '7/03/2012';
var new_date = fix_date(start_date);
console.log(new_date); // 2012/03/7​
http://www.webdevelopersnotes.com/tips/html/10_ways_to_format_time_and_date_using_javascript.php3
and this
http://www.elated.com/articles/working-with-dates/
Basically, you have 3 methods and you have to combine the strings for yourself:
getDate(): Returns the date
getMonth(): Returns the month
getFullYear(): Returns the year
<script type="text/javascript">
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //months are zero based
var curr_year = d.getFullYear();
document.write(curr_date + "-" + curr_month + "-" + curr_year);
</script>
check this answer link

JavaScript Date / Time Conversion

I have dates and times in a database in the following format:
2011-08-02T00:00:00-00:00
What is the easiest way to convert them to something like 8-2-2011?
Thanks,
var date = "2011-08-02T00:00:00-00:00".split('T')[0].split('-').reverse();
var month = date[0], day = date[1];
//remove 0 in the beginning if not necessary
if (+month < 10) {
month = month.slice(1);
}
if (+day < 10) {
day = day.slice(1);
}
//swap between the two
date[0] = day;
date[1] = month;
date.join('-');
Or you can use the boring Date way.
Here's the code:
x=new Date("2011-08-02T00:00:00-00:00")
str=(x.getUTCMonth()+1)+"-"+x.getUTCDate()+"-"+x.getUTCFullYear()
Or:
x="2011-08-02T00:00:00-00:00"
x=/^(\d+)\-(\d+)\-(\d+)/.exec(x)
if(x){
str=(parseInt(x[2],10)+"-"+parseInt(x[3],10)+"-"+parseInt(x[1],10))
}
This format will work in the Javascript Date constructor:
var d = new Date("2011-08-02T00:00:00-00:00");
var month = d.getUTCMonth() + 1;
var day = d.getUTCDate();
var year = d.getUTCFullYear();
var output = month + "-" + day + "-" + year;
one way could be to split up the date part
var date = "2011-08-02T00:00:00-00:00";
var dpart = (date.substr(0,10)).split("-");
var odate = parseInt(dpart[1],10)+"-"+parseInt(dpart[2],10)+"-"+dpart[0];

How to convert dateTime format in javascript

How i could convert datetime 5/8/2011 12:00:00 AM (m/d/yyyy) to dd-MMM-yyyy like 08-May-2011 in javascript.
This link is a good resource you can use for.
http://blog.stevenlevithan.com/archives/date-time-format
Alternatively, you need to get the individual part and concatenate them as needed like below.
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
var monthnumber = now.getMonth();
var monthday = now.getDate();
var year = now.getYear();
String myOutput = monthday + "-" + monthnumer + "-" + year;
To get the month name instead of month number, you need to define an array like below
var arrMonths = new Array ("Jan","Feb"....};
String myOutput = monthday + "-" + arrMonths[monthnumer-1] + "-" + year;
check below link hope you got some idea
http://bytes.com/topic/javascript/answers/519332-how-convert-datetime-format-using-javascript
http://blog.stevenlevithan.com/archives/date-time-format
similar question solution

Categories