Convert from dateTime string to javascript date object - javascript

I use this method in order to convert a date string to a javascript date object:
function convertToDateOrUndefined(dateString) {
if (dateString instanceof Date || dateString == null) {
return undefined;
}
return new Date(dateString.replace(/(\d{2})\.(\d{2})\.(\d{4})/,'$3-$2-$1'));
}
Currently I have this dateTime string 'dd.MM.yyyy HH:mm' and I would need also a function to convert this string into a js date obejct.
I am not really good in regex therefore I would need help - Thanks!

Look at the current regex. You know it returns a date from your dd.MM.yyyy format, right? So you can assume that the three (\d{n}) represent the day, month and year (\d means a digit, {n} means n times, so \d{2} mean two digits; the () groups each part so we can refer to them later).
In the second string, we take the parts the we got from the 1st one, and reorder them. $1 is the 1st group (the part of the regex inside the ()), $2 is the 2nd group, etc.
From there, the way to the solution is simple. We just need to add the time part:
new Date(dateString.replace(/(\d{2})\.(\d{2})\.(\d{4}) (\d{2}):(\d{2})/,'$3-$2-$1 $4:$5'));

A non regex solution. Hope this helps
var dateString = '25.12.2016 00:00';
var formattedDateString = dateString.split(' ')[0].split('.').reverse().join('-');
var dateObj = new Date(formattedDateString);
console.log(dateObj);

Related

Removing Character conditionally with specific position in Javascript

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").

Remove time after converting date toISOString

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);

JS Date: Add 0 in front of every single day or month

I have this date parsed from an api as a string:
DD-MM-YYYY but sometimes the date is DD-M-YYYY or even D-M-YYYY.
For example:
4-1-2013
or
10-10-2013
or 7-4-2013
The year is always 4 digits but days or months sometimes get one digit. How can I manually (with JS) add 0 in front of a every single digit ?
I am using moment.js for some calculations thus I am remove the '-' using
date.replace("-", "")
to get a whole number (eg. 4-1-2013 = 412013) so I can use it with moment.js but if its a single digit, it all gets messed up.
You can normalise your strings first like this:
date = date.replace(/\b(\d{1})\b/g, '0$1');
which will take any "word" that is just a single digit and prepend a zero.
Note that to globally replace every - you must use the regexp version of .replace - the string version you've used only replaces the first occurrence, therefore:
date = date.replace(/\b(\d{1})\b/g, '0$1').replace(/-/g, '');
will do everything you require.
Moment.js supports formats with dashes, so you don't even need to do any string handling.
moment('4-1-2013', 'MM-DD-YYYY').format("MMDDYYYY"); // 04012013
moment('10-10-2013', 'MM-DD-YYYY').format("MMDDYYYY"); // 10102013
If the date variable is in a String format(for example from input[type=date]) then you need to split the data component into single items.
date = date.split('-');
then check both the day's and the month's length
day = date[0].length==1 ? "0"+date[0] : date[0];
month = date[1].length==1 ? "0"+date[1] : date[1];
then get them back together into a format that you desire
date = ""+day+month+date[2];
Working example: http://jsfiddle.net/dzXPE/
var day = new Date();
day = day.getDay();
if(day.toString().length <= 1) {
day = '0' + day;
}
You can use the same for month. I'm not entirely sure you need to convert to string but it wouldn't hurt.

how to check if one date comes before anotherone in javascript

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
}
});

Is there a built-in JavaScript function to process a time string?

To make a time like "2009-05-02 00:00:00" to "2009-05-02".
I know I can achieve this by a regular expression, but is there a built-in function that can do this?
There's no built-in date function that can do that. As a matter of fact if you create a new Date object in JavaScript with that date format, you get an Invalid Date Error.
You are correct in using a regular expression or string manipulation in this case.
Here's a list of all the JavaScript Date Functions.
To simply get the date portion of the string and display it without converting into a Date Object. You can simply do this:
var dateString = "2009-05-02 00:00:00"
alert(dateString.substring(0,10)); // Will show "2009-05-02"
To convert this string into a proper JavaScript Date Object, you can use this snippet:
function sqlTimeStampToDate(timestamp) {
// This function parses SQL datetime string and returns a JavaScript Date object
// The input has to be in this format: 2007-06-05 15:26:02
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]);
}
The format will be "ddd MMM dd YYYY hh:mm:ss" + TimeOffSet, but you will be able to use any of the standard JavaScript date functions.
See below for two simple methods to get a date format of "2009-05-02", from the initial format, that is "2009-05-02 00:00:00".
<script type="text/javascript">
var mydate, newdate1, newdate2;
mydate = "2009-05-02 00:00:00";
newdate1 = (mydate.split(/ /))[0];
alert('newdate 1: ' + newdate1);
newdate2 = mydate.substr(0,10);
alert('newdate 2: ' + newdate2);
</script>
You might find this helpful:
Return today's date and time
How to use the Date() method to get today's date.
getTime()
Use getTime() to calculate the years since 1970.
setFullYear()
How to use setFullYear() to set a specific date.
toUTCString()
How to use toUTCString() to convert today's date (according to UTC) to a string.
getDay()
Use getDay() and an array to write a weekday, and not just a number.
This is copy-paste from www.w3schools.com since I can't post a link to it...
Or just search Google for "JavaScript date function" or related. Regular expressions are used to match specific parts of strings, which is useful in searching, extraction and replacement, not really anything that would help you with formatting a date.

Categories

Resources