Javascript get and format current date [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Formatting a date in JavaScript
I need to show a current date in format like this (some examples):
sep 10, 2012
nov 5, 2012
and so on.
Using javascript I get a current date object
var date = new Date();
what I need to do next?

you can use this.
function dateTest(){
var d =new Date();
var month_name=new Array(12);
month_name[0]="Jan"
month_name[1]="Feb"
month_name[2]="Mar"
month_name[3]="Apr"
month_name[4]="May"
month_name[5]="Jun"
month_name[6]="Jul"
month_name[7]="Aug"
month_name[8]="Sep"
month_name[9]="Oct"
month_name[10]="Nov"
month_name[11]="Dec"
alert(month_name[d.getMonth()]+" "+d.getDate()+" , "+d.getFullYear());
}

You can use the getMonth (including some switch/case for the text), the getDate and the getFullYear methods to build your string.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/prototype#Methods

Use dateFormat lib available in following link
http://stevenlevithan.com/assets/misc/date.format.js
Refer this article for formatting js using above lib.
http://blog.stevenlevithan.com/archives/date-time-format
Edit:
If you cant use lib then
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
var formattedDate = curr_date + " " + curr_month + ", " + curr_year;

Try this
function getCurrentDate(){
var now=new Date();
var date=now.getDate();
var year=now.getFullYear();
var months=new Array('jan', 'feb', 'mar' ... 'dec');
var month=months[now.getMonth()]
return month + ' ' + date + ', ' + year;
}

EDITED
You can use this function in your code :
function getFormattedDate(input){
var pattern=/(.*?)\/(.*?)\/(.*?)$/;
var result = input.replace(pattern,function(match,p1,p2,p3){
var months=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Dec'];
return (months[(p1-1)]+" "+p2<10?"0"+p2:p2)+" "+p3;
});
alert(result);
}
And for ref. you can call this function directly like this:
getFormattedDate("11/18/2013");
OR you can use this code, too.
var date = new Date();
dateFormat(date,"mediumDate");
you can also find further different formats here.

Related

angularjs - calculate a date plus one day

I need to get the date one day after another date.
I do :
$scope.date2.setDate($scope.date1.getDate()+1);
if
$scope.date1 = 2015-11-27
then
$scope.date2 = 2015-11-28
It s ok,
but when
$scope.date1 = 2015-12-02
then
$scope.date2 = 2015-11-28 (ie tomorrow)
I don't understand why...
If anyone knows..
try this instead efficient simple pure JS
var todayDate = new Date();
console.log(new Date().setDate(todayDate.getDate()+1));
so you will have that same Date type object and hence you don't need to go with moment.js
Use moment.js for this momentjs
var startdate = "2015-12-02";
var new_date = moment(startdate, "YYYY-MM-DD").add('days', 1);
var day = new_date.format('DD');
var month = new_date.format('MM');
var year = new_date.format('YYYY');
alert(new_date);
alert(day + '.' + month + '.' + year);

Changing Date format in JavaScript [duplicate]

This question already has answers here:
Get String in YYYYMMDD format from JS date object?
(53 answers)
Closed 9 years ago.
var dt="29/05/2013"; //DD/MM/YYYY
I want to convert to yyyy/MM/dd format;
The approach I've used is:
var newdate=dt.getFullYear()+"/"+dt.getMonth()+"/"+dt.getDate();
Is there any simple approach to convert it with out using substring?
I don't want to use plugins by the way...
var dt = "29/05/2013";
var newdt = dt.split('/').reverse().join('/');
Fiddle:http://jsfiddle.net/4WGnC/
Consider using a library to help you: http://www.datejs.com/ and http://momentjs.com/ are good libraries.
Date.parse ("29/05/2013").toString("yyyy/MM/dd")
simply try like this
var a = dt.split("/");
var new_date = a[2]+'/'+a[1]+'/'+a[0];
alert(new_date);
If you are using jquery ui..
var newdate = $.datepicker.formatDate('yy/mm/dd', new Date());
Look this Example:
var d = new Date ( "January 6, 1972" );
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);
Hope it will help you!

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

Add days to date using Javascript

I am trying to add days to a given date using Javascript. I have the following code:
function onChange(e) {
var datepicker = $("#DatePicker").val();
alert(datepicker);
var joindate = new Date(datepicker);
alert(joindate);
var numberOfDaysToAdd = 1;
joindate.setDate(joindate + numberOfDaysToAdd);
var dd = joindate.getDate();
var mm = joindate.getMonth() + 1;
var y = joindate.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
$('.new').val(joinFormattedDate);
}
On first alert I get the date 24/06/2011 but on second alert I get Thu Dec 06 2012 00:00:00 GMT+0500 (Pakistan Standard Time) which is wrong I want it to remain 24/06/2011 so that I can add days to it. In my code I want my final output to be 25/06/2011.
Fiddle is # http://jsfiddle.net/tassadaque/rEe4v/
Date('string') will attempt to parse the string as m/d/yyyy. The string 24/06/2011 thus becomes Dec 6, 2012. Reason: 24 is treated as a month... 1 => January 2011, 13 => January 2012 hence 24 => December 2012. I hope you understand what I mean. So:
var dmy = "24/06/2011".split("/"); // "24/06/2011" should be pulled from $("#DatePicker").val() instead
var joindate = new Date(
parseInt(dmy[2], 10),
parseInt(dmy[1], 10) - 1,
parseInt(dmy[0], 10)
);
alert(joindate); // Fri Jun 24 2011 00:00:00 GMT+0500 (West Asia Standard Time)
joindate.setDate(joindate.getDate() + 1); // substitute 1 with actual number of days to add
alert(joindate); // Sat Jun 25 2011 00:00:00 GMT+0500 (West Asia Standard Time)
alert(
("0" + joindate.getDate()).slice(-2) + "/" +
("0" + (joindate.getMonth() + 1)).slice(-2) + "/" +
joindate.getFullYear()
);
Demo here
I would like to encourage you to use DateJS library. It is really awesome!
function onChange(e) {
var date = Date.parse($("#DatePicker").val()); //You might want to tweak this to as per your needs.
var new_date = date.add(n).days();
$('.new').val(new_date.toString('M/d/yyyy'); //You might want to tweak this as per your needs as well.
}
Assuming numberOfDaysToAdd is a number:
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
The first alert is the value of the field. the second is the generated date from a non-US formatted date.
Here is a working example (seems that this kind of markup is necessary to get noticed)
If you want to keep your code, then you need to change
var joindate = new Date(datepicker);
to
var parms = datepicker.split("/");
then use
var joindate = new Date(parms[1]+"/"+parms[0]+"/"+parms[2]);
OR the identically working
var joindate = new Date(parms[2],parms[1]-1,parms[0]);
As pointed out in a few other answers too, use the .getDate()
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
Lastly you want to add a 0 if the month is < 10
if (mm<10) mm="0"+mm;
If you are using the datepicker from jQuery UI, then you can do
$('.new').val($("#DatePicker").datepicker( "setDate" , +1 ).val());
instead of your function
http://jqueryui.com/demos/datepicker/#method-setDate
Sets the current date for the
datepicker. The new date may be a Date
object or a string in the current date
format (e.g. '01/26/2009'), a number
of days from today (e.g. +7) or a
string of values and periods ('y' for
years, 'm' for months, 'w' for weeks,
'd' for days, e.g. '+1m +7d'), or null
to clear the selected date.
Try
function onChange(e) {
var datepicker = $("#DatePicker").val();
alert(datepicker);
var parts = datepicker.split(/[^\d]/);
var joindate = new Date();
joindate.setFullYear(parts[2], parts[1]-1, parts[0]);
alert(joindate);
var numberOfDaysToAdd = 1;
joindate.setDate(joindate + numberOfDaysToAdd);
var dd = joindate.getDate();
var mm = joindate.getMonth() + 1;
var y = joindate.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
$('.new').val(joinFormattedDate);
}
I suppose the problem is JavaScript expects format MM/DD/YYYY not DD/MM/YYYY when passed into Date constructor.
To answer your real problem, I think your issue is that you're trying to parse the text-value of the DatePicker, when that's not in the right format for your locale.
Instead of .val(), use:
var joindate = $('#DatePicker').datepicker("getDate");
to get the underyling Date() object representing the selected date directly from jQuery.
This guarantees that the date object is correct regardless of the date format specified in the DatePicker or the current locale.
Then use:
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
to move it on.
Is it a typo round joindate.setDate(joindate + numberOfDaysToAdd)?
I tried this code, it seems ok to me
var joindate = new Date(2010, 5, 24);
alert(joindate);
var numberOfDaysToAdd = 1;
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
var dd = joindate.getDate();
var mm = joindate.getMonth() + 1;
var y = joindate.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
alert(joinFormattedDate);
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + days);
return this;
};
and in your javascript code you could call
var currentDate = new Date();
// to add 8 days to current date
currentDate.addDays(8);
function onChange(e) {
var datepicker = $("#DatePicker").val().split("/");
var joindate = new Date();
var numberOfDaysToAdd = 1;
joindate.setFullYear(parseInt(datepicker[2]), parseInt(datepicker[1])-1, parseInt(datepicker[0])+numberOfDaysToAdd);
$('.new').val(joindate);
}
http://jsfiddle.net/roberkules/k4GM5/
try this.
Date.prototype.addDay = function(numberOfDaysToAdd){
this.setTime(this.getTime() + (numberOfDaysToAdd * 86400000));
};
function onChange(e) {
var date = new Date(Date.parse($("#DatePicker").val()));
date.addDay(1);
var dd = date.getDate();
var mm = date.getMonth() + 1;
var y = date.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
$('.new').val(joinFormattedDate);
}

Get todays date in Javascript

How can I get the current date in Javascript in this format?
"M/D/YYYY"?
Thanks.
If this would be today it would be
"2/17/2011", if it was the 3rd it would be "2/3/2011".
Thanks
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(month + "/" + day + "/" + year)
I assigned each part into its own variable for this example so that it's more clear as to what it returns.
Use the javascript Date object:
var d = new Date();
alert((d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear());
Steven Levithan's (stevenlevithan.com) dateFormat function looks really versatile to me.
See:
http://blog.stevenlevithan.com/archives/date-time-format
In his code, he adds dateFormat in as a prototype method for Date.
// For convenience...
Date.prototype.format = function (mask, utc) {
return dateFormat(this, mask, utc);
};
So you can use it as a method on a Date object.
var now = new Date();
var variable=now.format("m/dd/yy");
document.write(variable);
HTH
Rich

Categories