I have 2 dates and I one to check if one date comes before another one.
I know you have to parse the date to a JS date object and then check it with milliseconds.
But the problem is, in my database dateTimes are stored like this.
10-mei-2012 09:36
So my question is how can I compare two of these dates and check that date 1 comes before date2? Oh and for the record, I am also using jquery to get these values.
var dateB = $('#DATUM_BEGIN').val();
var dateE = $('#DATUM_EINDE').val();
kind regards
Stef
In that format you can compare strings as-is, it is safe. So use just
if (dateB < dateE) ...
http://www.datejs.com/ could be helpful. it is a jquery Plugin to compare Dates.
The format you show is "mostly" ISO-8601 combined-date format which is by design comparable as plain text.
The only difference between what you have and pure ISO-8601 is that there would need to be a 'T' where the space character is.
http://en.wikipedia.org/wiki/ISO_8601
So, if you can sort the strings you know which one comes first.
Here's a function found while googling that converts MySQL DATETIME to a JS Object
function mysqlTimeStampToDate(timestamp) {
var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
}
Here's one example of how to use it:
$(function(){
var dateB = mysqlTimeStampToDate($('#DATUM_BEGIN').val());
var dateE = mysqlTimeStampToDate($('#DATUM_EINDE').val());
if(dateB < dateE){
// dateB is older
} else {
// dateB is newer
}
});
Related
This is my data format:
"21/03/2019 19:18"
The problem i am facing is, when ever if i am dealing with date or time there is an issue with the month ( it has 03 instead of 3 ). I am using library called date-fns. And also i have tried with the help of javascript date objects without using library, but no luck still the month should not have zero in-front of it.
So, how to remove the "0" in-front of "3", and one more problem is how to do this conditionally , because when its Dec, i will be getting data as "21/12/2019 19:18". So, in this case , i should not remove "1" as its located in same position of "0" in previous scenario.
In other words, i want to remove "0" by checking if there is "1" presented in that position or index, if presented then remove else remove "0"
How to achieve this.
I tried the below code:
const d = new Date(2019,03,21)
But, its says legacy error. So when i removed "0" infront of "3" it works fine. Please help
I assume you get the data back as a string and you just want to remove leading zeros from the 2nd number only?
we can use .split to break up the string into parts, and then we can use parseInt to convert some string parts into numbers. that will turn the string "03" into the number 3
function removeleadingZerosFromDateString(str) {
//Break up the date string on the slashes and whitespace, so we have an array of all the parts
var parts = str.split(/\/|\s/);
console.log(parts);
//Assign each array item to a variable so we can see what is what
var day = parseInt(parts[0], 10);
var month = parseInt(parts[1], 10);
var year = parts[2];
var time = parts[3];
var meridian = parts[4];
return day+'/'+month+'/'+year+' '+time+' '+meridian;
}
var result = removeleadingZerosFromDateString("21/03/2019 19:18 PM");
console.log(result);
You said you were using date-fns, so I'll give an answer in that regard.
The current 1.x version doesn't support parsing strings in a custom format, but they are adding that to 2.x, and you can use the alpha release to try it today.
The syntax is:
var date = parse(dateString, formatString, baseDate, [options]);
See the documentation for the parse function in version 2.0.0-alpha.27.
In your case, it would be like this:
var date = parse("21/03/2019 19:18", "MM/dd/yyyy HH:mm", new Date());
Lastly, if you want to use a library for this but don't want to experiment with an alpha, you can either wait for Date-fns 2.0 to become final, or you can try Luxon or Moment - both of which already have this functionality (though Moment uses a slightly different token format "MM/DD/YYYY HH:mm").
how can I remove the time after converting a date to ISO String?
var now = new Date();
console.log( now.toISOString() );
if the output is
2017-10-19T16:00:00.000Z
I just want it to be :
2017-10-19
One simple but robust approach is to split along the date separator:
new Date().toISOString().split('T', 1)[0] // => '2019-03-18'
If working with an ISO string of unknown origin, using a Regex pattern as the splitter may prove more reliable (ie. Postgres uses a whitespace as the separator).
const isoString = '2019-01-01 12:00:00.000000'
isoString.split(/[T ]/i, 1)[0] // => '2019-01-01'
Unlike using substring, this approach does not make assumptions about the length of the date (which might prove false for years before 1000 and after 9999).
There are actually many ways to do so:
1- Use Moment JS which gives you kind of flexibility in dealing with the issue
2- The simple way to do it in native JS is to use substring() function like that:
var date = new Date();
console.log(date.toISOString().substring(0,10));
The second way would be more effective if all you need is to remove the time part of the string and use the date only.
Here's how it would be done with momentjs
var currentDate = moment().format('YYYY-MM-DD');
Check out the Jsfiddle link: https://jsfiddle.net/cgbcc075/
It's better to use moment in js for date time related functions. Instantly now you can use substring method:
var a = "2017-10-19T16:00:00.000Z"
a = a.substring(0,10)
The easiest way is just to use split
var now = new Date();
console.log(now.toISOString().split('T')[0]);
Computationally fastest way (ie: no unnecessary allocations) would be slicing up to index 10, since ISO8601 timestamp strings have these elements guaranteed, at least for the years 0000 to 9999.
let currentDate = new Date().toISOString().substring(0,10);
I have getting a dateformat like '23.10.2017'. I need to format this in to
'10/23/2017'
I just tried
var crDate='23.10.2017';
var newDateF=new Date(crdate).toUTCString();
but it showing InvalidDate
can anyone help to change the format.
Thanks in advance
I don't think using Date() is the solution. You can do
var crDate = '23.10.2017';
var newDateF = crDate.split(".");
var temp = newDateF[0];
newDateF[0] = newDateF[1];
newDateF[1] = temp;
newDateF.join("/");
This splits the string into an array, swaps the first and second elements, and then joins back on a slash.
A regex replacement will do the trick without any Date functions.
var date = '23.10.2017';
var regex = /([0-9]{2})\.([0-9]{2})\.([0-9]{4})/;
console.log(date.replace(regex,'$2/$1/$3'));
Just use moment.js if you can :
// convert a date from/to specific format
moment("23.10.2017", "DD.MM.YYYY").format('MM/DD/YYYY')
// get the current date in a specific format
moment().format('MM/DD/YYYY')
Moment is a very usefull and powerfull date/time library for Javascript.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Extending JavaScript's Date.parse to allow for DD/MM/YYYY (non-US formatted dates)?
Convert dd-mm-yyyy string to date
Entered a date in textbox, for example: 05/09/1985, and I wanted to convert it to 05-Sep-1985 (dd-MMM-yyyy) format. How would I achieve this? Note that the source format may be dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format.
Code Snippet:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val());
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
This code returns 09-May-1985 but I want 05-Sep-1985. Thanks.
You might want to use helper library like http://momentjs.com/ which wraps the native javascript date object for easier manipulations
Then you can do things like:
var day = moment("12-25-1995", "MM-DD-YYYY");
or
var day = moment("25/12/1995", "DD/MM/YYYY");
then operate on the date
day.add('days', 7)
and to get the native javascript date
day.toDate();
Update
Below you've said:
Sorry, i can't predict date format before, it should be like dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format finally i wanted to convert all this format to dd-MMM-yyyy format.
That completely changes the question. It'll be much more complex if you can't control the format. There is nothing built into JavaScript that will let you specify a date format. Officially, the only date format supported by JavaScript is a simplified version of ISO-8601: yyyy-mm-dd, although in practice almost all browsers also support yyyy/mm/dd as well. But other than that, you have to write the code yourself or (and this makes much more sense) use a good library. I'd probably use a library like moment.js or DateJS (although DateJS hasn't been maintained in years).
Original answer:
If the format is always dd/mm/yyyy, then this is trivial:
var parts = str.split("/");
var dt = new Date(parseInt(parts[2], 10),
parseInt(parts[1], 10) - 1,
parseInt(parts[0], 10));
split splits a string on the given delimiter. Then we use parseInt to convert the strings into numbers, and we use the new Date constructor to build a Date from those parts: The third part will be the year, the second part the month, and the first part the day. Date uses zero-based month numbers, and so we have to subtract one from the month number.
Date.parse recognizes only specific formats, and you don't have the option of telling it what your input format is. In this case it thinks that the input is in the format mm/dd/yyyy, so the result is wrong.
To fix this, you need either to parse the input yourself (e.g. with String.split) and then manually construct a Date object, or use a more full-featured library such as datejs.
Example for manual parsing:
var input = $('#' + controlName).val();
var parts = str.split("/");
var d1 = new Date(Number(parts[2]), Number(parts[1]) - 1, Number(parts[0]));
Example using date.js:
var input = $('#' + controlName).val();
var d1 = Date.parseExact(input, "d/M/yyyy");
Try this:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val().toString().replace(/([0-9]+)\/([0-9]+)/,'$2/$1'));
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
The RegExp replace .replace(/([0-9]+)\/([0-9]+)/,'$2/$1') change day/month position.
See this http://blog.stevenlevithan.com/archives/date-time-format
you can do anything with date.
file : http://stevenlevithan.com/assets/misc/date.format.js
add this to your html code using script tag and to use you can use it as :
var now = new Date();
now.format("m/dd/yy");
// Returns, e.g., 6/09/07
Note that this seems like a question that is asked many times, but somehow I can't get the most common solution to work.
Most answers revolve around a solution like this one:
function isValidDate(){
var dateString = '2001/24/33';
return !isNaN(Date.parse(dateString));
}
In Firefox this returns a false as the result of that Date.parse is a number; 1041462000000.
How do I fix this..?
A good way to do this is to create new date object based on the string and compare the result of that object with the input string. If it is not the same, the date was invalid and JS did a fallback to a closer (valid) date. Something like this:
function isValidDate(str){
var split = str.split('/');
var date = new Date(split[0], split[1]-1, split[2]);
return (date.getFullYear() == split[0] && date.getMonth()+1 == split[1] && date.getDate() == split[2]);
}
call with:
var isValid = isValidDate('2001/24/33');
Note: in this case the input string is assumed to be in a specific format. If your sure that it's always the same format there is not problem. If not, your need the work some more on this code.
As a sidenote: Use moment.js if you need to do extensive date operations.
I suggest to use http://www.datejs.com/.
Very cool library.