Javascript - reorder and reformat date - javascript

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

Related

Javascript Split and Match the pattern array

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

How to Get 'a.m.' format in moment.js

I'm having trouble to find the format for making like :
6 a.m.
I'm wondering if someone know which string i need to enter to outputFormat
for make it the format as describe.
moment(openTime, inputFormat).format(outputFormat)
This format:
'a.m.'
Moment.js doesn't have the exact format output you want, but you can produce it using two .replaces afterwards.
var m = moment();
var s = m.format('h a');
console.log(s);
s = s.replace('am', 'a.m.').replace('pm', 'p.m.');
console.log(s);
m = m.add(12, 'hours');
s = m.format('h a');
console.log(s);
s = s.replace('am', 'a.m.').replace('pm', 'p.m.');
console.log(s);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.28.0/moment.min.js"></script>

Rearrange date format jQuery or javascript

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 can I get a string date in the format "2016-07-06T10:57Z" from Date() and toISOString

I need to get a date in this format:
2016-07-06T10:57Z
Using this code I have been able to get a date in a format somewhat like I need:
var isoDate = new Date().toISOString();
2016-07-06T08:46:08.127Z
But is there a way I can remove the seconds and fraction of seconds from the date so it appears exactly like the date: "2016-07-06T10:57Z" ?
You will always want to remove the last 8 characters ('Z' included) thus you can use a function like slice
isoDate = isoDate.slice(0, -8); //Remove seconds + fractions + Z
isoDate += "Z"; //Add back the Z
You can use this way because the format returned by toISOString() will always be
YYYY-MM-DDTHH:mm:ss.sssZ
Please try
var isoDate = new Date().toISOString();
var pos = isoDate.lastIndexOf(':');
var datePart1 = isoDate.substring(0,pos);
var datePart2 = isoDate.substr(-1, 1);
var dateStr = datePart1+datePart2;
console.log(dateStr);

convert my date to timestamp in javascript

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

Categories