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
Related
I'm trying to convert a MM/DD/YYYY date to a long date. So for example, 02/16/2020 would convert to something like 16/02/2020.
Is there a way to make this date conversion accurately?
You need to specify the original format of the time, and then convert it to a new format.
const date = "02/16/2020";
alert(moment(date, "MM/DD/YYYY").format('DD/MM/YYYY'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Use moment for date formatting:
Sample Code:
moment('02/16/2020').format('16/02/2020');
You can play with date by moment.js. It is very useful tool for javascript developer.
Momemet Js Document
For dynamic value:
moment(yourDate, 'MM/DD/YYYY').format('DD/MM/YYYY');
Here, yourDate is your dynamic value date.
check this. its work.
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [day,month,year].join('/');
}
document.getElementById('res').innerHTML = formatDate('02/16/2020') ;
<div id="res">res</div>
2 || 1 liners ?
var src = '02/16/2020'
var a = src.split('/');
console.log(a.concat(a.splice(0, 2)).join('/'));
console.log(src.replace(/(\d+)\/(\d+)\/(\d+)/, '$3/$1/$2'));
If you want a conversion just between the exact formats you have mentioned:
function dfConvert(f) {
var farr = f.split("/");
return `${farr[1]}/${farr[0]}/${farr[2]}`;
}
var input = "02/16/2020";
console.log(`input: ${input}`)
console.log(`output: ${dfConvert(input)}`);
If you want the actual date object and from that you want your mentioned format for some reason:
function toDate(f) {
var farr = f.split("/");
return new Date(parseInt(farr[2]), parseInt(farr[0])-1, parseInt(farr[1]))
}
function dfConvert(f) {
var d = toDate(f)
var day = d.getDate()
var month = (d.getMonth() + 1)
var year = d.getFullYear()
return `${((day.toString().length <= 1) ? "0": "")}${day}/${((month.toString().length <= 1) ? "0": "")}${month}/${year}`
}
var input = "02/16/2020"
console.log(`input: ${input}`)
console.log(`output: ${dfConvert(input)}`)
Hope it helps
Sorry for posting this simple question. Application is going to be deployed soon, and recently a bug came, but i am not able to figure out why it is comming.
Created A JS_BIN this is the link
http://jsbin.com/razufavuru/1/edit?html,js,output
Error is minDate: 0 is disabling today's date also while i want to disable only past dates.
This is jquery code:
$("#leaveEndDate").datepicker(
{
minDate: 0,
beforeShowDay : disablePublicHolidaysAndWeekends,
minDate : dateToday,
onSelect : function(dateText, inst) {
var firstDate = $("#leaveStartDate").datepicker('getDate');
var selDate = null;
selDate = $(this).datepicker('getDate');
var lastDate = selDate;
if (lastDate < firstDate) {
$("#leaveEndDate").val('');
$("#endDateError").html(
"End Date must be greater than Start Date");
$(inst).datepicker('show');
} else {
$("#endDateError").html("");
calculateDays(firstDate, lastDate);
}
}
});
Disable Holiday and Weekends Method is
function disablePublicHolidaysAndWeekends(date) {
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
if(day < 10 && day > 0){
day = '0'+day;
}
var getdate = year+ '/' + '0' +(month + 1) + '/' + day;
for (var i = 0; i < publicHolidayDates.length; i++) {
if ($.inArray( getdate ,publicHolidayDates) != -1 || new Date() > date) {
return [ false ];
}
}
var noWeekend = $.datepicker.noWeekends(date);
return !noWeekend[0] ? noWeekend : [ true ];
}
this is the img
public holidays are comming from database.
It confuse me lot when this code for another datapicker works.
$("#targetDate").datepicker({
beforeShowDay : $.datepicker.noWeekends,
minDate : 0
});
Here it do not disable today date.
this is the img
jQuery Datepicker value minDate expect value of type
Type: Date or Number or String
Try minDate: new Date() instead, or minDate: '0'
UPDATE:
What causes your issue is your custom function:
function disablePublicHolidaysAndWeekends(date) {
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
if(day < 10 && day > 0){
day = '0'+day;
}
if(month < 9 && month > 0){ //added control over month, as you would have got errors for month=10, 11, 12 in the below variable getdate
month = '0' +(month + 1);
}
else{
month += 1;
}
var getdate = year+ '/' + month + '/' + day;
for (var i = 0; i < publicHolidayDates.length; i++) {
//removed "|| new Date() > date"
if ($.inArray( getdate ,publicHolidayDates) !== -1 ) {
return [ false ];
}
}
var noWeekend = $.datepicker.noWeekends(date);
return !noWeekend[0] ? noWeekend : [ true ];
}
Read this about Date comparison in javascript
Fiddle here
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:
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('/');
}