This question already has answers here:
Format date to MM/dd/yyyy in JavaScript [duplicate]
(3 answers)
Closed 3 years ago.
How can I convert the following date format below (Mon Nov 19 13:29:40 2012)
into:
dd/mm/yyyy
<html>
<head>
<script type="text/javascript">
function test(){
var d = Date()
alert(d)
}
</script>
</head>
<body>
<input onclick="test()" type="button" value="test" name="test">
</body>
</html>
Some JavaScript engines can parse that format directly, which makes the task pretty easy:
function convertDate(inputFormat) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(inputFormat)
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/')
}
console.log(convertDate('Mon Nov 19 13:29:40 2012')) // => "19/11/2012"
This will ensure you get a two-digit day and month.
function formattedDate(d = new Date) {
let month = String(d.getMonth() + 1);
let day = String(d.getDate());
const year = String(d.getFullYear());
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return `${day}/${month}/${year}`;
}
Or terser:
function formattedDate(d = new Date) {
return [d.getDate(), d.getMonth()+1, d.getFullYear()]
.map(n => n < 10 ? `0${n}` : `${n}`).join('/');
}
Related
This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript? [duplicate]
(4 answers)
Closed 3 years ago.
I need to convert the current timestamp (Eg: 1578293326452) to yyyy-mm-dd hh:mm:ss format
using javascript.
I obtained the current timestamp as follows:
var date = new Date();
var timestamp = date.getTime();
How can I change the format?
function getTime(){
var date = new Date();
var year = date.getFullYear();
var month = (date.getMonth() +1);
var day = date.getDate();
var hour = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();
return formateTime(year, month, day, hour, minute, second);
}
function formateTime(year, month, day, hour, minute, second){
return makeDoubleDigit(year) + "-" +
makeDoubleDigit(month) + "-" +
makeDoubleDigit(day) + " " +
makeDoubleDigit(hour) + ":" +
makeDoubleDigit(minute) + ":" +
makeDoubleDigit(second);
}
function makeDoubleDigit(x){
return (x < 10) ? "0" + x : x;
}
console.log(getTime())
Maybe this is what you need
d = Date.now();
d = new Date(d);
d = (d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear()+' '+(d.getHours() > 12 ? d.getHours() - 12 : d.getHours())+':'+d.getMinutes()+' '+(d.getHours() >= 12 ? "PM" : "AM");
console.log(d);
This question already has answers here:
Reformat string containing date with Javascript
(3 answers)
Closed 5 years ago.
var dates = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewData["ph"]));
//dates[0] = 16-09-2017
//date = 09/16/2017
$('#StartDate').datepicker({
dateFormat: JsDateFormat,
autoclose: true,
beforeShowDay: function (date) {
for (var i = 0; i < dates.length; i++) {
if (new Date(dates[i]).toString() == date.toString()) {
console.log(date);
return [true, 'ui-state-highlight highlight-red', name[i]];
}
}
return [true];
}
});
how to change the date format from '09/16/2017' to '16-09-2017'?
i had tried
new Date('dd-M-yy', date).toString() - not working
date.toString('dd-M-yy') - not working
Since you're using datepicker you can use $.datepicker.formatDate
Here is a snippet using formatDate to compare the dates in the array:
var dates = ['10-10-2017', '25-10-2017', '29-10-2017'];
$('#StartDate').datepicker({
dateFormat: "d/m/yy",
autoclose: true,
beforeShowDay: function (date) {
for (var i = 0; i < dates.length; i++) {
if (dates[i] == $.datepicker.formatDate('dd-mm-yy', date)) {
console.log(date);
return [true, 'ui-state-highlight highlight-red', name[i]];
}
}
return [true];
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<input type="text" id="StartDate" name="StartDate"/>
ViewData["ph"] the date time will be converted to string with culture of the server in which the application is running so be sure to convert with this format in the server and assign to the ViewData.
If value passed to JsonConvert is a type of Date object then make use of the formating parameter to the method SerializeObject
JsonConvert.SerializeObject(this, Formatting.None, new IsoDateTimeConverter() {
DateTimeFormat = "dd-M-yy" });
If you want to convert date to string refer the answer provide by #rahul mr
for all browsers
function formattedDate(d) {
var month = d.getMonth() + 1;
var day = d.getDate();
var year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return day + '/' + month + '/' + year;
}
function formattedDate(d = new Date) {
let month = String(d.getMonth() + 1);
let day = String(d.getDate());
const year = String(d.getFullYear());
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return `${day}/${month}/${year}`;
}
this function returns date in format you needed
Please how do I format a today's date in javascript so it will output something like '2013-05-24 03:21:12' that i can insert into database datetime field.? Thanks in advance..
Dates? Times? Give Moment.js a shot
dateToString : function (unformatted) {
if (!unformatted) {
return null;
}
var year = unformatted.getFullYear();
var month = unformatted.getMonth() + 1;
var day = unformatted.getDate();
if (month < 10) {
month = '0' + month;
}
if (day < 10) {
day = '0' + day;
}
return [year, month, day].join('-');
}
feel free to add time formatting
This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 9 years ago.
I want to change YYYY-MM-DD HH:MM:SS to MM-DD-YYYY
Example:
I have a string which represents a date in this format: 2013-06-15 03:00:00
I want to change this string into 06-15-2013 using JavaScript.
Is there any library to do this? or should i just use JavaScript?
function change(time) {
var r = time.match(/^\s*([0-9]+)\s*-\s*([0-9]+)\s*-\s*([0-9]+)(.*)$/);
return r[2]+"-"+r[3]+"-"+r[1]+r[4];
}
change("2013-06-15 03:00:00");
see moment.js.. i found it very useful
http://momentjs.com/
DEMO: http://jsfiddle.net/abc123/f6k3H/1/
Javascript:
var d = new Date();
var c = new Date('2013-06-15 03:00:00');
alert(formatDate(c));
alert(formatDate(d));
function formatDate(d)
{
var month = d.getMonth();
var day = d.getDate();
month = month + 1;
month = month + "";
if (month.length == 1)
{
month = "0" + month;
}
day = day + "";
if (day.length == 1)
{
day = "0" + day;
}
return month + '-' + day + '-' + d.getFullYear();
}
Since this doesn't use RegEx you'll notice some weirdness....Examples:
d.getMonth() + 1
this is because getMonth is 0 indexed....
day = day + "";
if (day.length == 1)
{
day = "0" + day;
}
this is because hours, seconds, minutes all return 1 digit when they are 1 digit...this makes them return a leading 0. The same can be done to Month and Day if desired.
This question already has answers here:
JavaScript function to add X months to a date
(24 answers)
Closed 9 years ago.
I want to add 1 Month or 6 Month to a given Date.
But if i add one Month, the year isnt incremented. And if i add 6 Month to June, i got the Month 00 returned BUT the year is incremented.
Could you please help me out?
function addToBis(monthToAdd){
var tmp = $("#terminbis").val().split('.');
var day = tmp[0];
var month = tmp[1];
var year = tmp[2];
var terminDate = new Date(parseInt(year),parseInt(month), parseInt(day));
terminDate.setMonth(terminDate.getMonth()+monthToAdd);
day = "";
month = "";
year = "";
if(terminDate.getDate() < 10){
day = "0"+terminDate.getDate();
} else{
day = terminDate.getDate();
}
if(terminDate.getMonth() < 10){
month = "0"+terminDate.getMonth();
} else{
month = terminDate.getMonth();
}
year = terminDate.getFullYear();
$("#terminbis").val(day+"."+month+"."+year);
}
getMonth returns a number from 0 to 11 which means 0 for January , 1 for february ...etc
so modify like this
var terminDate = new Date(parseInt(year),parseInt(month - 1), parseInt(day));
terminDate.setMonth(terminDate.getMonth()+monthToAdd);
and
month = terminDate.getMonth() + 1;
You should use the javascript Date object's native methods to update it. Check out this question's accepted answer for example, it is the correct approach to your problem.
Javascript function to add X months to a date
The function can be written much more concisely as:
function addToBis(monthToAdd){
function z(n) {return (n<10? '0':'') + n}
var tmp = $("#terminbis").val().split('.');
var d = new Date(tmp[2], --tmp[1], tmp[0]);
d.setMonth(d.getMonth() + monthToAdd);
$("#terminbis").val(z(d.getDate()) + '.' + z(d.getMonth() + 1)
+ '.' + d.getFullYear();
}
The value of terminbis and monthToAdd should be validated before use, as should the date generated from the value.