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);
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").
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.
I am looking for a way to get minutes only from a date in string (coming from toISOString).
When using Date object, I was using getTime(), but dont think there is a direct method available for ISO format.
Would I need to extract strings directly from ISO format, as its just a string?
Code:
var depTime = new Date(1222332000).toISOString();
This gives me "1970-01-15T03:32:12.000Z", so what is a good way to get minutes which is "32".
You can use getMinutes() from the date object:
var d = new Date('1970-01-15T03:32:12.000Z');
console.log(d.getMinutes());
This is the right method, but, if there are issues with the Time Zone, you can parse the string:
var depTime = new Date(1222332000).toISOString();
console.log(depTime.split(":")[1]); // 32
You can use
deptime.getMinutes(); // 32
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMinutes
Since it's just a string, regex should work just fine.
T\d+:(\d+)
Can anyone help me with this ?
var current_date=new Date('2012/12/21 22:59:59.997');
var result=current_date.getTime();
Im not getting result in Firefox but it does show in chrome, in FF it shows invalid date.
You should be able to do the following (using date.setMilliseconds):
var dateString = '2012/12/21 22:59:59.997';
var dateStringSplit = dateString.split('.');
var myDate = new Date(dateStringSplit[0]);
myDate.setMilliseconds(dateStringSplit[1]);
console.log(myDate);
Firefox and some other browsers (namely, Safari or Opera) don't like milliseconds.
// Split off the part after the dot
var current_date = new Date('2012/12/21 22:59:59.997'.split('.')[0]);
// Works everywhere!
var result = current_date.getTime();
If you really want to work with milliseconds, you have to split the date in multiple parts and use new Date() with those. From MDN documentation, here are the options:
new Date(year, month, day [, hour, minute, second, millisecond])
Or, as h2ooooooo says, you can use the second part of the split date and use setMilliseconds.
Overall, you have plenty of solutions. Choose the one that annoys you the least.
The format you are using is not a standard format for Date.parse
You may want to split the string and set the parts individually. Also, please manage the time zone correctly as it is not apparent which timezone the date string is in.
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
}
});