How to get date from a timestamp? - javascript

I have 2 timestamps with different format:
1/2/2021 21:15
19-3-2021 21:15
Is there a method in javascript to get just the date for these timestamps?
Expected output:
'1/2/2021'
'19/3/2021'
I know using substr() is not effective as the length of the date string can vary.

Assuming the two timestamp formats are the only ones to which you need to cater, we can try:
function getDate(input) {
return input.replace(/\s+\d{1,2}:\d{1,2}$/, "")
.replace(/-/g, "/");
}
console.log(getDate("1/2/2021 21:15"));
console.log(getDate("19-3-2021 21:15"));
The first regex replacement strips off the trailing time component, and the second replacement replaces dash with forward slash.

Use split() to convert string into array based on space.
Then use replaceAll() on each element of the array, which will replace all the dash(-) which are in dates to slash (/)
Use includes() to check if slash(/) is present or not, as it will separate data(d/m/y) with time(h:m)
function getDateFun(timestamp) {
let timeStr = timestamp;
let splitStamp = timeStr.split(" ");
let dates = [];
for (let i = 0; i < splitStamp.length; i++) {
if (splitStamp[i].includes("/") || splitStamp[i].includes("-"))
dates.push(splitStamp[i]);
}
console.log(dates.toString());
}
getDateFun("1/2/2021 21:15");
getDateFun("19-3-2021 21:15");
getDateFun("1/2/2021 21:15 19-3-2021 21:15");
Update
Based on RobG comment, the same can be achieved by using Regular Expressions and replace() method.
function getDateFun(timestamp){
return timestamp.split(' ')[0]
.replace(/\D/g, '/');
}
console.log(getDateFun("28/03/2021 07:50"));
console.log(getDateFun("19-02-2021 15:30"));
function getDateFun(timestamp){
return timestamp
.replace(/(\d+)\D(\d+)\D(\d+).*/,'$1/$2/$3')
}
console.log(getDateFun("28/03/2021 07:50"));
console.log(getDateFun("19-02-2021 15:30"));

Assuming that your dates have a space character between the date and time you can use the split() method:
let firstDate = '1/2/2021 21:15';
let secondDate = '19-3-2021 21:15';
// [0] is the first element of the splitted string
console.log(firstDate.split(" ")[0]);
console.log(secondDate.split(" ")[0]);
Or you can then also use substr() by first finding the position of the space character:
let firstDate = '1/2/2021 21:15';
let secondDate = '19-3-2021 21:15';
let index1 = firstDate.indexOf(' ');
let index2 = secondDate.indexOf(' ');
console.log(firstDate.substr(0, index1));
console.log(secondDate.substr(0, index2));

Related

Javascript using regular expression to get date in middle of object

I have this object "FILTER_DATE":"LAST_MONTH", "FROM_DATE":"2/9/2020", "TO_DATE":"3/9/2020" and need to extract the FROM_DATE value 2/9/2020. I am trying to use replace, to replace everything before and after the from date with an empty string, but I'm not sure how to get both sides of the value.
at the moment I can remove everything up until the date value with this... /.*FROM_DATE":"/ but how can I now remove the final part of the object?
Thanks
If you need to make it with replace, just use:
const input = '"FILTER_DATE":"LAST_MONTH", "FROM_DATE":"2/9/2020", "TO_DATE":"3/9/2020"';
const date = input.replace(/^.*"FROM_DATE":"([\d/]+)".*$/, '$1');
Now you can use date with just the date in it...
In a second time you could remove /",.*/, but this seems too much heuristic to me.
You'd better just catch the first capturing group from the following regex:
/FROM_DATE":"([0-9][0-9]?\/[0-9][0-9]?\/[0-9][0-9][0-9][0-9])"/
let str = '"FILTER_DATE":"LAST_MONTH", "FROM_DATE":"2/9/2020", "TO_DATE":"3/9/2020"';
let pattern = /FROM_DATE":"([0-9][0-9]?\/[0-9][0-9]?\/[0-9][0-9][0-9][0-9])"/
alert(str.match(pattern)[1]);
Your sample string looks very much like JSON. So much so in fact that you could just wrap it in braces, parse it as and object, and get the value of the FROM_DATE.
EG:
function almostJsonStringToObject(str) {
return JSON.parse('{' + str + '}');
}
var str = '"FILTER_DATE":"LAST_MONTH", "FROM_DATE":"2/9/2020", "TO_DATE":"3/9/2020"';
var obj = almostJsonStringToObject(str);
var fromdate = obj.FROM_DATE;
console.log(fromdate);

How to replace 3rd hyphen with empty space and 4th hyphen with colon in Javascript

"2017-12-31-19-40" // Date Format
I have date format like above. I want to convert this string to proper date format like
"2017-12-31 19:40"
I tried like this:
var str = "2017-12-31-19-40";
var newStr = str.indexOf("-");
var newStr2 = str.indexOf("-", newStr+4)
var newStr3 = str[newStr2].replace(" ");
alert(newStr3);
But it giving me only hyphen. how can I do this?
Regex replacement is a good option here:
var input = "2017-12-31-19-40";
console.log(input);
input = input.replace(/(\d{4}-\d{2}-\d{2})-(\d{2})-(\d{2})/, "$1 $2:$3");
console.log(input);
The clean way will be by using moment.js library.
const date = moment('2017-12-31-19-40','YYYY-MM-DD-HH-mm');
console.log(date.format('YYYY-MM-DD HH:mm'))

String cutting with Javascript

I have a string like "home/back/step" new string must be like "home/back".
In other words, I have to remove the last word with '/'. Initial string always has a different length, but the format is the same "word1/word2/word3/word4/word5...."
var x = "home/back/step";
var splitted = x.split("/");
splitted.pop();
var str = splitted.join("/");
console.log(str);
Take the string and split using ("/"), then remove the last element of array and re-join with ("/")
Use substr and remove everything after the last /
let str = "home/back/step";
let result = str.substr(0, str.lastIndexOf("/"));
console.log(result);
You could use arrays to remove the last word
const text = 'home/back/step';
const removeLastWord = s =>{
let a = s.split('/');
a.pop();
return a.join('/');
}
console.log(removeLastWord(text));
Seems I got a solution
var s = "your/string/fft";
var withoutLastChunk = s.slice(0, s.lastIndexOf("/"));
console.log(withoutLastChunk)
You can turn a string in javascript into an array of values using the split() function. (pass it the value you want to split on)
var inputString = 'home/back/step'
var arrayOfValues = inputString.split('/');
Once you have an array, you can remove the final value using pop()
arrayOfValues.pop()
You can convert an array back to a string with the join function (pass it the character to place in between your values)
return arrayOfValues.join('/')
The final function would look like:
function cutString(inputString) {
var arrayOfValues = inputString.split('/')
arrayOfValues.pop()
return arrayOfValues.join('/')
}
console.log(cutString('home/back/step'))
You can split the string on the '/', remove the last element with pop() and then join again the elements with '/'.
Something like:
str.split('/');
str.pop();
str.join('/');
Where str is the variable with your text.

how can I format string like 9:34, 18:00 to format of 00:00

I am gathering time in different forms like 9:34, 18:00. these are strings and I need to keep them strings, while keeping sure they are always following format of "00:00"
If it just the matter of adding leading 0. This will work
var str = "9:45";
('0'+str).slice(-5); //09:45
var str = "19:45";
('0'+str).slice(-5); //19:45
You can use replace() with regex
var time = '9:34, 19:00:01, 18:00';
document.write(time
.replace(/\b\d:\d{2}(\b|:)/g, '0$&')
// for replacing time in format X:XX to 0X:XX
.replace(/(\b\d{2}:\d{2}):\d{2}\b/g, '$1')
// for replacing time in format XX:XX:XX to XX:XX
)
If the minute and second parts are also unpredictable, then you would need to fix that as well.
var t1 = '9:3';
var t2 = t1.split(':').map(function(part) {
return ('0' + part).slice(-2);
}).join(':');
console.log(t2);

How to split an array index

how to split an array index i.e.. sample code
var parts = currentVal.split(" ");
var datePart = parts.splice(0,1);
alert("Date: " + datePart );
var timePart = parts.join(' ');
here i am validating the date time regular expression. var datePart is an array index, now i want to split datepart ....
var parts1 = datePart.split('/');
parts1.date = parseInt(parts1[0]);
parts1.month = parseInt(parts1[1]);
parts1.year = parseInt(parts1[2]);
but it is showing uncaught type error, their is no method split(); Can any one help me how do i separate date, month, year.
If you're trying to just check whether a string represents a valid date or not, I would personally recommend the magical Date object that javascript natively supports. Through some sort of wizardry it can read the date in almost any format you throw at it, and if it is an invalid date it will evaluate to the string Invalid Date.
So to check if currentVal is a valid date, do:
if (new Date(currentVal) == 'Invalid Date') {
... // The date is invalid
} else {
... // The date is valid
}
On the other hand, if you need to use a specific regex to validate the date, you could either do something like
var parts = currentVal.split(' ');
var dateParts = parts[0].split('/');
var timePart = parts[1]; // Maybe you want to split this as well?
And this would leave dateParts as an array containing the month, day and year.
I think you are looking for the function explode().
http://php.net/manual/en/function.explode.php
Actually function splice returns an array of removed elements, so to solve you problem you just need to apply split on the first element of datePart array:
var parts1 = datePart[0].split("/");

Categories