how to sort milatry format date in javascript - javascript

i want to sort date in ascending order in javascript function.i am having date in following format 3/4/2014 1300
im having follwing array which contains date
categoriesdata.push(RecordDate);
categoriesdata.sort(function (a, b) {
var key1 = a.RecordDate;
var key2 = b.RecordDate;
if (key1 < key2) {
return -1;
} else if (key1 == key2) {
return 0;
} else {
return 1;
}
})
categoriesdata have the following record
3/4/2014 1300
2/4/2014 0000
1/31/2014 1030
now i want to sort these record in such way so that i will get following output
1/31/2014 1030
2/4/2014 0000
3/4/2014 1300

you have to split the date string and get the parts using regex or simple split
var date = "1/31/2014 1030".split(" ");
var day = parseInt(date[0].split["/"][0], 10);
var month = parseInt(date[0].split["/"][1], 10) - 1;
var year = parseInt(date[0].split["/"][2], 10);
var hours = parseInt(date[1].slice(0,2), 10);
var minutes = parseInt(date[1].slice(2,4), 10);
then create Date objects from them in javascript.
var dateObj = new Date(year, month, day, hour);
then convert the dates to be compared to "milliseconds since beginning"
var milliseconds1 = Date.parse(dateObj)
similarly convert both dates to be compared in milliseconds, now you will have two numbers that can easily be compared
Incorporate this idea to your sort function.
categoriesdata.push(RecordDate);
categoriesdata.sort(function (a, b) {
var key1 = a.RecordDate;
var key2 = b.RecordDate;
var getTimestamp = function (dateString) {
var date = dateString.split(" ");
var day = parseInt(date[0].split["/"][0], 10);
var month = parseInt(date[0].split["/"][1], 10) - 1;
var year = parseInt(date[0].split["/"][2], 10);
var hours = parseInt(date[1].slice(0, 2), 10);
var minutes = parseInt(date[1].slice(2, 4), 10);
return Date.parse(new Date(year, month, day, hour));
}
key1 = getTimestamp(key1);
key2 = getTimestamp(key2);
if (key1 < key2) {
return -1;
} else if (key1 == key2) {
return 0;
} else {
return 1;
}
})

Best way is to convert it to a date type. And after sorting convert it back to the string you want
For sorting dates there are plenty of solutions. Read this Sort Javascript Object Array By Date

Related

How to manipulate date using Javascript

How can I achieve this sequence of date output if the user input is 04-29-2022 and the output is like this
What I want:
2022-05-14
2022-05-29
2022-06-14
2022-06-29
2022-07-14
2022-07-29
2022-08-14
2022-08-29
my code output
2022-05-13
2022-05-28
2022-06-12
2022-06-27
2022-07-12
2022-07-27
2022-08-11
2022-08-26
var dateRelease = new Date("04-29-2022")
const terms = 8
for (let i = 0; i < terms; i++) {
console.log(new Date(dateRelease.setDate(dateRelease.getDate() + 15)).toISOString().slice(0, 10))
}
Here is a function that takes the day of the month in the given date and determines which other date of the month would be needed in the output (either 15 more or 15 less). Then it generates dates alternating between those two date-of-the-month, and when it is the lesser of those two, incrementing the month. In case a date is invalid and automatically overflows into the next month, it is corrected to the last day of the intended month.
To format the date in the output, it is better to not use toISODateString as that interprets the date as a UTC Date, while new Date("2022-04-29") interprets the given string as a date in the local time zone. This can lead to surprises in some time zones. So I would suggest using toLocaleDateString with a locale that produces your desired format.
Here is the code:
function createSchedule(date, count) {
date = new Date(date);
let day = date.getDate();
let k = +(day > 15);
let days = k ? [day - 15, day] : [day, day + 15];
let result = [];
for (let i = 0; i < count; i++) {
k = 1 - k;
date.setDate(days[k]);
// When date overflows into next month, take last day of month
if (date.getDate() !== days[k]) date.setDate(0);
if (!k) date.setMonth(date.getMonth() + 1);
result.push(date.toLocaleDateString("en-SE"));
}
return result;
}
var dateRelease = new Date("2022-04-29");
var result = createSchedule(dateRelease, 25);
console.log(result);
var dateRelease = new Date("04-29-2022")
const terms = 8
for (let i = 0; i < terms; i++) {
let date = new Date(dateRelease.setDate(dateRelease.getDate() + 15)).toLocaleDateString('en-US');
let format = date.split('/').map(d => d.padStart(2 ,'0')).join('-')
console.log(format);
}

Check if a date is between two dates

I have an array with different dates with the format of year-month-day.
something like this:
var dates = ["2016-08-01", "2016-08-09", "2016-08-10", ....];
I also have a function that formats todays date in the same format as above. And is stored in a variable:
var currentDate; //Contains current date in the format of year-month-day
What i need to do is to check if any of the dates in the array, either:
Match with today's date.- e.g. Today would be 2016-08-13
Match with 14 days back from today's date. - e.g. 14 days back from today (2016-08-13) would be 2016-07-30
Or match with any dates between the current and 14 days back.
I'm trying to do this by looping through the array, checking each value. But im unsure about the if condition/conditions
for(var i = 0; i < dates.length; i++) {
if(currentDate === *condition*) {
sendDate(dates[i]);
}
}
Anyone have a good solution for this? Thanks in advance!
Firstly, create a new Date() from your currentDate ( currentDate is string format Y-d-m with hour and minutes is 00:00)
var current = new Date(currentDate);
var matchWithCurrent = [];
var matchWithDayBack = [];
var between = [];
just loop through your date array
for (var i=0; i<dates.length; i++) {
var tmpDate = new Date(dates[i]); //Convert string to date
var diff = Math.ceil((current - tmpDate) / (1000 * 3600 * 24)); //get time difference (current - tmpDate is milisecond, we need convert it to day)
// Check condition and push it on array correct
if (diff == 0) {
matchWithCurrent.push(dates[i]);
}
if (diff == 14) {
matchWithDayBack.push(dates[i]);
}
if ((diff > 0) && (diff <14)) {
between.push(dates[i]);
}
}
console.log(matchWithCurrent);
console.log(matchWithDayBack);
console.log(between);
If you want only one array match with 3 condition just check 3 condition in only one if and push it into your result array
One way would be to parse the dates to millisecond values and compare them.
var todayParts = currentDate.split('-');
var today = new Date(todayParts[0], todayParts[1], todayParts[2]).getTime();
var otherParts = dates[i].split('-');
var other = new Date(otherParts[0], otherParts[1], otherParts[2]).getTime();
if (today < other + 1209600000 /* 2 weeks in milliseconds */) {
// The other date is less than 2 weeks before today
}
You can read here why I parsed it manually instead of using Date.parse().
You can compare two dates something like that:
var currentDate = new Date();
for(var i = 0; i < dates.length; i++) {<br>
var arrDate = new Date(dates[i]);
if(currentDate == arrDate)
{//compare array dates with current date
//your code here
}
var beforeDate = (currentDate.getDate() - 14); //14 days before
if(arrDate >= beforeDate && arrDate <= currentDate){
//compare dates between current date and 14 days before date
}
}

How to filter the data using date from JSON format

I want to filter using date but the data is in JSON format. How can I filter the large dataset using date in JavaScript?
Example:
data=[{date:'22-12-2014',name:'selva'},{date:'10-10-2010',name:'raja'},{date:'11-11- 2011',name:'suresh'}]
If you simply want to filter data by time, you can look through all objects in the array like this:
var filteredData = [];
for(var index in data) {
var obj = data[index];
var date = parseDate(obj.date);
//Filter dates from 2011 and newer
if(date > new Date(2011, 0, 1))
filteredData.push(obj);
}
function parseDate(dateStr) {
var date = dateStr.split('-');
var day = date[0];
var month = date[1] - 1; //January = 0
var year = date[2];
return new Date(year, month, day);
}
//Filtered data now contains:
// [{"date":"22-12-2014","name":"selva"},{"date":"11-11- 2011","name":"suresh"}]
I am sure you could do the parse date better, by for example defining the date in a format that the Date constructor accepts.
To grab the set of elements that match a certain date you can use filter to extract them into a new array.
function getByDate(date){
return data.filter(function (el) {
return el.date == date;
});
}
var arr = getByDate('11-11-2011');
To to sort your dataset by date you need to convert your date strings to a JS date object first. That involves adjusting the date string slightly so it can be parsed properly.
function reformatDate(date) {
return arr = date.split('-').reverse();
}
var sortByDate = function (a, b) {
return new Date(reformatDate(a.date)) - new Date(reformatDate(b.date));
};
data.sort(sortByDate);
JSFiddle demo
I used date format MM/DD/YY. Here is the full example -
var data=[
{date:'02/10/2018',name:'date is 10'},
{date:'02/14/2018',name:'date is 14'},
{date:'02/16/2018',name:'date is 16'},
{date:'02/20/2018',name:'date is 20'},
{date:'02/24/2018',name:'date is 24'},
{date:'02/26/2018',name:'date is 26'},
{date:'02/30/2018',name:'date is 30'},
{date:'03/01/2018',name:'date is 01'},
{date:'03/05/2018',name:'date is 05'},
{date:'02/23/2018',name:'date is name 23'},
]
var today = new Date();
var todayTime = new Date().getTime();
var days_after_20 = new Date().setDate(today.getDate()+20);
var days_before_5 = new Date().setDate(today.getDate()-5);
var result = data.filter(function (item) {
var itemTime = new Date(item.date).getTime()
return itemTime >= days_before_5 && itemTime <= days_after_20;
})
console.log(result);
To fetch the set of elements that match a certain date you can use filter to extract them into a new array.
var tempArray= data.filter(function (d, i) {
return d >= startDate && d <= endDate;
})

Sorting JSON object in javascript by date (String)

I have a JSON object in JavaScript and I am trying to sort the object in order by dates.
fileListObj[id] = date;
output : "#HIDDEN ID": "16/12/2013"
How can I sort the object to be in order by most recent date?
I only know how to do this in php
include moment.js
fileListObj.sort(function(a,b) {
return moment(b, 'DD/MM/YYYY').valueOf() - moment(a, 'DD/MM/YYYY').valueOf();
})
First you'll want to write/get a date parser. Using Javascript's native Date object is unreliable for parsing raw strings.
Then you'll want to use Array.prototype.sort():
function parseDate(input) {
var parts = input.split('/');
return new Date(parts[2], parts[1]-1, parts[0]);
}
function sortAsc(a,b)
{ return parseDate(a.date) > parseDate(b.date); }
function sortDesc(a,b)
{ return parseDate(a.date) < parseDate(b.date); }
list.sort(sortAsc);
Here's a working example, the sorted table will contain ISO format dates
var dates = ["12/05/2012", "09/06/2011","09/11/2012"]
var sorted=[];
for(var i=0, i= dates.length;i++){
var p = dates[i].split(/\D+/g);
sorted[i]= new Date(p[2],p[1],p[0]);
}
alert(sorted.sort(function(a,b){return b-a}).join("\n"));
To get the same input format you can use this function:
function formatDate(d)
{
date = new Date(d)
var dd = date.getDate();
var mm = date.getMonth()+1;
var yyyy = date.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm};
return d = dd+'/'+mm+'/'+yyyy
}
sorted.sort(function(a,b){return b-a})
formatSorted = []
for(var i=0; i<sorted.length; i++)
{
formatSorted.push(formatDate(sorted[i]))
}
alert(formatSorted.join("\n"));

How can I compare two time strings in the format HH:MM:SS?

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

Categories

Resources