Javascript get and format current date [duplicate]

 ̄綄美尐妖づ 提交于 2019-12-06 05:04:48

问题


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?


回答1:


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());
 }



回答2:


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




回答3:


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;




回答4:


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;
}



回答5:


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.



来源:https://stackoverflow.com/questions/13513144/javascript-get-and-format-current-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!