I am trying to get the pattern from a string in JavaScript, where my string is 01-01-2000 - 01-01-2010 here I want to make these both date separate like date1 = 01-01-2000 and date2 = 01-01-2010.
I have tried this code :
var date = "01-01-2000 - 01-01-2010";
var date2 = date.match(/([0-9]{2})-([0-9]{2})-([0-9]{4})/);
console.log(date2[0]);
output: 01-01-2000 [correct]
but I using console.log(date2[1]) it displaying 01 only.
Please help how to achieve the goal make this function.
expecting output :
date[0]: 01-01-2000
date[1]: 01-01-2010
You can give a try to String.matchAll() which returns an iterator of all results matching a string against a regular expression, including capturing groups.
Demo :
var date = "01-01-2000 - 01-01-2010";
var date2 = [ ...date.matchAll(/([0-9]{2})-([0-9]{2})-([0-9]{4})/g) ];
for (const match of date2) {
console.log(match[0])
}
You Can use split instead If your date format is fixed.
var date = "01-01-2000 - 01-01-2010";
var date2 = date.split(" - ")
console.log(date2);
if you want to work with pattern you only have to add the /g in the end for global search into the string:
var date = "01-01-2000 - 01-01-2010";
var date2 = date.match(/([0-9]{2})-([0-9]{2})-([0-9]{4})/g);
console.log(date2[0]);
console.log(date2[1]);
Related
I have a date displaying on my website in this format:
MM/DD/YY
I would like to convert it to the following format using jQuery:
YYYY-MM-DD
I would prefer to do it without a plugin. I was able to replace the forward slashes with hyphens using the code below but now I am stuck.
var date = "05/23/21";
var formattedDate = date.replace(/\//g, '-');
$('body').append(formattedDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
To do what you require you can convert the input string to a Date object, then use the methods JS exposes to pull out the constituent parts in to the format you require:
let input = "05/23/21";
let date = new Date(input);
const zeroPad = (num, places) => String(num).padStart(places, '0')
let formattedDate = `${date.getFullYear()}-${zeroPad(date.getMonth() + 1, 2)}-${zeroPad(date.getDate(), 2)}`;
$('body').append(formattedDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This method assumes all dates are 20XX. It splits the date by /, reverses that array (getting the YY MM DD format), then reformats the year to be YYYY and joins the array back together with -
var date = "05/23/21";
var formattedDate = date.split('/').reverse().map((e, i) => i === 0 ? `20${e}` : e).join('-');
$('body').append(formattedDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
By using regex group and replace it with reverse order you can do it.
var date = "05/23/21";
const formattedDate = date.replace(/(\d+)\/(\d+)\/(\d+)/, "20$3-$2-$1");
console.log(formattedDate);
.as-console-wrapper{min-height: 100%!important; top: 0}
Please check the following code. Let me know if something goes wrong
const d = date.split("/");
var res = '20'+d[2] +'-'+d[0]+'-'+d[1];
Hello I have a function that generates the date with this format:
MM-DD-YYYY
Is there any jquery or javascript trick to convert that value into:
YYYY-MM-DD?
More Detailed Explanation:
The function I have generates the date and stored in a variable called tdate
So var tdate = 01-30-2001
I would like to do some jquery or javascript to turn tdate into:
tdate = 2001-01-30
tdate is a string
Thanks!
You can use .split(), destructuring assignment, termplate literal to place yyyy, mm, dd in any order
var date = "01-30-2001";
var [mm, dd, yyyy] = date.split("-");
var revdate = `${yyyy}-${mm}-${dd}`;
console.log(revdate)
You can use a little bit regex to capture year, month and day and reorder them:
var tdate = "01-30-2001";
console.log(
tdate.replace(/^(\d{2})-(\d{2})-(\d{4})$/, "$3-$1-$2")
)
Can slice() up the string and put it back together the way you want it
var tdate = '01-30-2001';
tdate = [tdate.slice(-4), tdate.slice(0,5)].join('-');
// or tdate = tdate.slice(-4) + '-' + tdate.slice(0,5)
console.log(tdate)
you can split the string on '-' and then re arrange the array once and join again to form the date.
var date = "01-30-2001";
var arr = date.split("-");
var revdate = arr.splice(-1).concat(arr.splice(0,2)).join('-');
console.log(revdate);
How do I convert the value 24/05/2016 (typeof(24/05/2016) is number) for a Date using JavaScript?
While performing the following error occurs:
transactionDateAsString.split is not a function"
var transactionDateAsString = 24/05/2015;
var parts = transactionDateAsString.split("/");
var dudu = parts + '';
var date = new Date(dudu[2], dudu[1] - 1, dudu[0]);
console.log(date);
Not sure why you are adding an empty string at some point. This is how it should be:
var transactionDateAsString = '24/05/2015';
var parts = transactionDateAsString.split("/");
var date = new Date(parts[2],parts[1]-1,parts[0]);
alert(date);
Also note the quotes around the date as string.
How to convert my date to timestamp i dont know where im doing wrong.Any suggestion please ?
var dates = '27-04-2015';
var date1 = new Date(dates).getTime();
alert(date1);
Parameter you passed in the new Date('27-04-2015') is not valid. Use sepeartor '/' for change date format and send to the new Date('27/04/2015').
var dates = '27-04-2015';
var dates1 = dates.split("-");
var newDate = dates1[1]+"/"+dates1[0]+"/"+dates1[2];
alert(new Date(newDate).getTime());
Working Fiddle
Date constructor takes argument in mm-dd-yyyy format, try this
var timeStamp = function(str) {
return new Date(str.replace(/^(\d{2}\-)(\d{2}\-)(\d{4})$/,
'$2$1$3')).getTime();
};
alert(timeStamp('27-04-2015'));
Here, I had used RegExp to swap the format from dd-mm-yyyy to mm-dd-yyyy. So '27-04-2015' gives '04-27-2015'. In the expression (\d{2}\-)(\d{2}\-)(\d{4}), \d denotes integer, {} for length, () for grouping, \ to escape special characters like -.
var date = '28/05/2011 12:05';
var elem = date.split('');
hours = elem[0];
I have the above date format, please tell me how to split this, so that I can obtain 12 (hours) from this string?
var date = '28/05/2011 12:05';
var hrs = date.split(' ')[1].split(':')[0];
You can use a single call to split each component using a regular expression:
var date = '28/05/2011 12:05';
var elem = date.split(/[/ :]/);
alert(elem[3]); //-> 12
Working example: http://jsfiddle.net/gZ9c7/
A RegEx solution:
var myRe = /([0-9]+):[0-9]+$/i;
var myArray = myRe.exec("28/05/2011 12:05");
alert(myArray[1]); // 12
Some additional info:
Working code sample here.
About RegEx in JS.
As long as it's a consistent format:
var hours = date.split(' ')[1].split(':')[0]
is pretty easy.
when working with Dates it's better to use dedicated date/time functions:
var date = '28/05/2011 12:05';
var ms = Date.parse(date)
alert(new Date(ms).getHours())