I'm trying to convert date format (DD-MM-YYYY) to (YYYY-MM-DD).i use this javascript code.it's doesn't work.
function calbill()
{
var edate=document.getElementById("edate").value; //03-11-2014
var myDate = new Date(edate);
console.log(myDate);
var d = myDate.getDate();
var m = myDate.getMonth();
m += 1;
var y = myDate.getFullYear();
var newdate=(y+ "-" + m + "-" + d);
alert (""+newdate); //It's display "NaN-NaN-NaN"
}
This should do the magic
var date = "03-11-2014";
var newdate = date.split("-").reverse().join("-");
Don't use the Date constructor to parse strings, it's extremely unreliable. If you just want to reformat a DD-MM-YYYY string to YYYY-MM-DD then just do that:
function reformatDateString(s) {
var b = s.split(/\D/);
return b.reverse().join('-');
}
console.log(reformatDateString('25-12-2014')); // 2014-12-25
You can use the following to convert DD-MM-YYYY to YYYY-MM-DD format using JavaScript:
var date = "24/09/2018";
date = date.split("/").reverse().join("/");
var date2 = "24-09-2018";
date2 = date.split("-").reverse().join("-");
console.log(date); //print "2018/09/24"
console.log(date2); //print "2018-09-24"
You just need to use return newdate:
function calbill()
{
var edate=document.getElementById("edate").value;
var myDate = new Date(edate);
console.log(myDate);
var d = myDate.getDate();
var m = myDate.getMonth();
m += 1;
var y = myDate.getFullYear();
var newdate=(y+ "-" + m + "-" + d);
return newdate;
}
demo
But I would simply recommend you to use like #Ehsan answered for you.
First yo have to add a moment js cdn which is easily available at here
then follow this code
moment(moment('13-01-2020', 'DD-MM-YYYY')).format('YYYY-MM-DD');
// will return 2020-01-13
I am using jquery autocomplete onselect it is showing data in different text field. I am showing formatted date in #dob and #anniversery by using format_date() function
select: function(event, ui) {
$("#customerId").val(ui.item.id);
$("#customerName").val(ui.item.value);
var datefield = new Date(ui.item.dob);
$("#dob").val(format_date(datefield));
var datefield1 = new Date(ui.item.anni);
$("#anniversery").val(format_date(datefield1));
$("#address").val(ui.item.address);
$("#mobNo").val(ui.item.mobno);
},
});
function format_date(dt) {
alert(dt);
var dd = dt.getDate();
var mm = dt.getMonth() + 1; //January is 0!
var yyyy = dt.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
dt = mm + '/' + dd + '/' + yyyy;
return dt;
}
});
Above code is working properly if ui.item.dob and ui.item.anni is not null.
In case of null it is showing NaN/NaN/NaN
If date value is empty it should not show anything in textbox.
alert(dt) prints Invalide date.
How to resolve this.
You can check whether a Date instance is an invalid date by checking one of the properties for NaN:
function format_date(dt) {
if (isNaN(dt.getFullYear())) return "";
// ...
}
In your function, check that the Date object is okey using isNaN function. Also, there's an easier way of formating the date as you want, with out all the ifs:
function format_date(dt) {
if(isNaN(dt.getTime()) return "";
return dt.getFullYear + '/' + String('00' + (dt.getMonth() + 1)).slice(-2) + '-' + String('00' + dt.getDate()).slice(-2);
}
Also good to know is that initializing a Date object like var datefield = new Date(ui.item.dob); has a bit poor browser support (
A more safe way of doing it is to initialize the Date object without any proporties, var datefield = new Date(); and the using the Date set*() functions to set the time. A whole lot more code, but if you need it to work in old browsers...
Example
http://jsfiddle.net/HMb68/
var inDateTime = '2014-07-26 17:52:00',
inDateTimeSplit = inDateTime.split(' '),
inDateParts = inDateTimeSplit[0].split('-'),
inTimeParts = inDateTimeSplit[1].split(':'),
outDate = new Date;
outDate.setFullYear(parseInt(inDateParts[0], 10));
outDate.setMonth((parseInt(inDateParts[1], 10) - 1));
outDate.setDate(parseInt(inDateParts[2], 10));
outDate.setHours(parseInt(inTimeParts[0], 10));
outDate.setMinutes(parseInt(inTimeParts[1], 10));
outDate.setSeconds(parseInt(inTimeParts[2], 10));
outDate.setMilliseconds(0);
console.log(outDate);
I want to open the excel file and then save the excel file and the name will be file name + current date and time. I am not getting this result for date I have used Date()
var wshell;
var excel = new ActiveXObject("Excel.Application");
alert(excel);
var excel_file = excel.Workbooks.Open("book2.xlsx");
excel.Visible = true;
var objWorkbook = excel.Workbooks.Add();
var objWorksheet = objWorkbook.Worksheets(1);
objWorkbook.Worksheets(1).Activate;
objWorksheet.name = "test";
objWorksheet.Paste;
objWorksheet.columns.autofit;
window.clipboardData.setData("Text","");
var today = new Date();
document.write(today.toString());
excel_file.SaveAs("d:\\board.xls"+ (today.toString()));
alert("data saved");
today contains an illegal character (:) to use in a file name. You need to clean your date, for example something like this:
var today = new Date().toString().replace(/[^\w]/g, '');
And when saving, the timestamp should be a part of the file name instead of the extension:
excel_file.SaveAs("D:\\board" + today + ".xls");
Instead of .toString().replace() you can format the timestamp to look like you want with methods of Date object.
EDIT
Here's the code with which you can modify your dates. I've simplified getDate() for you, hence you can modify it to return a date in what ever form you want.
var today = new Date(),
time = today.toTimeString().split(':').join('').substr(0, 4),
timestamp = getDate('dd_mm_yyyy', today) + '_' + time;
function getDate (mode, userdate) {
var dte = userdate || new Date(),
d = dte.getDate().toString(),
m = (dte.getMonth() + 1).toString(),
yyyy = dte.getFullYear().toString(),
dd = (d.length < 2) ? '0' + d : d,
mm = (m.length < 2) ? '0' + m : m,
yy = yyyy.substring(2, 4);
switch (mode) {
case 'dd_mm_yyyy': return dd + '_' + mm + '_' + yyyy;
case 'yyyymmdd': return yyyy + mm + dd;
default: return dte;
}
}
timestamp contains a date in wanted form after run the code above.
JavaScript Check Date not today or in the past.
var c = '10 JUN 2010'; // this is the format of the date coming in.
var temp = new Array();
temp = c.split(' ');
var x = new Date ( temp[1]+" "+temp[0]+", "+temp[2] );
if (x.getTime() > getDate()) {
alertstring = alertstring + '\n\nDEBUG CODE: 1 ' + x + '\n\n';
}
I cannot change the format coming in.
Looks like you 99% have it. Here it is with a modified if condition:
var c = '10 JUN 2010'; // this is the format of the date coming in.
var temp = new Array();
temp = c.split(' ');
var x = new Date ( temp[1]+" "+temp[0]+", "+temp[2] );
if (x.getTime() > (new Date().getTime())) {
...
}
Update this line:
// Get current date and time
var today = new Date();
// strip time to compare to the parse date
if (x.getTime() > new Date(today.getFullYear(), today.getMonth(), today.getDate()).getTime()) {
// this date has not happened yet.
alertstring = alertstring + '\n\nDEBUG CODE: 1 ' + x + '\n\n';
}
Try to put in constructor the number of month
Instead of string .
Instead of June put 6.
I have two time strings in HH:MM:SS format. For example, str1 contains 10:20:45, str2 contains 5:10:10.
How can I compare the above values?
As Felix Kling said in the comments, provided your times are based on a 24 hour clock (and they should be if there's no AM/PM) and provided they are always in the format HH:MM:SS you can do a direct string comparison:
var str1 = "10:20:45",
str2 = "05:10:10";
if (str1 > str2)
alert("Time 1 is later than time 2");
else
alert("Time 2 is later than time 1");
Date.parse('01/01/2011 10:20:45') > Date.parse('01/01/2011 5:10:10')
> true
The 1st January is an arbitrary date, doesn't mean anything.
Date object in js support comparison, set them same date for compare hh:mm:ss :
new Date ('1/1/1999 ' + '10:20:45') > new Date ('1/1/1999 ' + '5:10:10')
> true
Try this code for the 24 hrs format of time.
<script type="text/javascript">
var a="12:23:35";
var b="15:32:12";
var aa1=a.split(":");
var aa2=b.split(":");
var d1=new Date(parseInt("2001",10),(parseInt("01",10))-1,parseInt("01",10),parseInt(aa1[0],10),parseInt(aa1[1],10),parseInt(aa1[2],10));
var d2=new Date(parseInt("2001",10),(parseInt("01",10))-1,parseInt("01",10),parseInt(aa2[0],10),parseInt(aa2[1],10),parseInt(aa2[2],10));
var dd1=d1.valueOf();
var dd2=d2.valueOf();
if(dd1<dd2)
{alert("b is greater");}
else alert("a is greater");
}
</script>
You can easily do it with below code:
Note: The second argument in RegExp is 'g' which is the global search flag.
The global search flag makes the RegExp search for a pattern throughout the string, creating an array of all occurrences it can find matching the given pattern. Below code only works if the time is in HH:MM:SS format i.e. 24 hour time format.
var regex = new RegExp(':', 'g'),
timeStr1 = '5:50:55',
timeStr2 = '6:17:05';
if(parseInt(timeStr1.replace(regex, ''), 10) < parseInt(timeStr2.replace(regex, ''), 10)){
console.log('timeStr1 is smaller then timeStr2');
} else {
console.log('timeStr2 is smaller then timeStr1');
}
Try this code.
var startTime = "05:01:20";
var endTime = "09:00:00";
var regExp = /(\d{1,2})\:(\d{1,2})\:(\d{1,2})/;
if(parseInt(endTime .replace(regExp, "$1$2$3")) > parseInt(startTime .replace(regExp, "$1$2$3"))){
alert("End time is greater");
}
Convert to seconds those strings:
var str1 = '10:20:45';
var str2 = '5:10:10';
str1 = str1.split(':');
str2 = str2.split(':');
totalSeconds1 = parseInt(str1[0] * 3600 + str1[1] * 60 + str1[0]);
totalSeconds2 = parseInt(str2[0] * 3600 + str2[1] * 60 + str2[0]);
// compare them
if (totalSeconds1 > totalSeconds2 ) { // etc...
Best way to compare times using convert into ms
var minutesOfDay = function(m){
return m.minutes() + m.hours() * 60;
}
return minutesOfDay(now) > minutesOfDay(end);
I improved this function from #kamil-p solution.
I ignored seconds compare . You can add seconds logic to this function by attention your using.
Work only for "HH:mm" time format.
function compareTime(str1, str2){
if(str1 === str2){
return 0;
}
var time1 = str1.split(':');
var time2 = str2.split(':');
if(eval(time1[0]) > eval(time2[0])){
return 1;
} else if(eval(time1[0]) == eval(time2[0]) && eval(time1[1]) > eval(time2[1])) {
return 1;
} else {
return -1;
}
}
example
alert(compareTime('8:30','11:20'));
Thanks to #kamil-p
I think you can put it like this.
var a = "10:20:45";
var b = "5:10:10";
var timeA = new Date();
timeA.setHours(a.split(":")[0],a.split(":")[1],a.split(":")[2]);
timeB = new Date();
timeB.setHours(b.split(":")[0],b.split(":")[1],b.split(":")[2]);
var x= "B is later than A";
if(timeA>timeB) x = "A is later than B";
document.getElementById("demo").innerHTML = x;
<p id="demo"></p>
Set the extracted part of the time to variables.
// If you don't have the second part then set it to 00.
//Create date object and set the time to that
var startTimeObject = new Date();
startTimeObject.setHours(startHour, startMinute, startSecond);
//Create date object and set the time to that
var endTimeObject = new Date(startTimeObject);
endTimeObject.setHours(endHour, endMinute, endSecond);
//Now we are ready to compare both the dates
if(startTimeObject > endTimeObject) {
alert('End time should be after start time.');
}
else {
alert('Entries are perfect.');
}
time format should be in HH:mm:ss HH for 24 hour format
if (start_time > end_time)
console.log('start time is greater than end time')
else console.log('end time is greater than start time')
You could compare the two values right after splitting them with ':'.
I'm not so comfortable with regular expressions, and my example results from a datetimepicker field formatted m/d/Y h:mA. In this legal example, you have to arrive before the actual deposition hearing. I use replace function to clean up the dates so that I can process them as Date objects and compare them.
function compareDateTimes() {
//date format ex "04/20/2017 01:30PM"
//the problem is that this format results in Invalid Date
//var d0 = new Date("04/20/2017 01:30PM"); => Invalid Date
var start_date = $(".letter #depo_arrival_time").val();
var end_date = $(".letter #depo_dateandtime").val();
if (start_date=="" || end_date=="") {
return;
}
//break it up for processing
var d1 = stringToDate(start_date);
var d2 = stringToDate(end_date);
var diff = d2.getTime() - d1.getTime();
if (diff < 0) {
end_date = moment(d2).format("MM/DD/YYYY hh:mA");
$(".letter #depo_arrival_time").val(end_date);
}
}
function stringToDate(the_date) {
var arrDate = the_date.split(" ");
var the_date = arrDate[0];
var the_time = arrDate[1];
var arrTime = the_time.split(":");
var blnPM = (arrTime[1].indexOf("PM") > -1);
//first fix the hour
if (blnPM) {
if (arrTime[0].indexOf("0")==0) {
var clean_hour = arrTime[0].substr(1,1);
arrTime[0] = Number(clean_hour) + 12;
}
arrTime[1] = arrTime[1].replace("PM", ":00");
} else {
arrTime[1] = arrTime[1].replace("AM", ":00");
}
var date_object = new Date(the_date);
//now replace the time
date_object = String(date_object).replace("00:00:00", arrTime.join(":"));
date_object = new Date(date_object);
return date_object;
}
var str1 = "150:05:05",
var str2 = "80:04:59";
function compareTime(str1, str2){
if(str1 === str2){
return 0;
}
var time1 = str1.split(':');
var time2 = str2.split(':');
for (var i = 0; i < time1.length; i++) {
if(time1[i] > time2[i]){
return 1;
} else if(time1[i] < time2[i]) {
return -1;
}
}
}
var startTime = getTime(document.getElementById('startTime').value);
var endTime = getTime(document.getElementById('endTime').value);
var sts = startTime.split(":");
var ets = endTime.split(":");
var stMin = (parseInt(sts[0]) * 60 + parseInt(sts[1]));
var etMin = (parseInt(ets[0]) * 60 + parseInt(ets[1]));
if( etMin > stMin) {
// do your stuff...
}