I have the following code on a page:
<span class="release-date"><i class="fa fa-calendar"></i> 2014-11-16</span>
This 2014-11-16 is the date and is generated automatically by my CMS. I need to change this date. Basically I need to change the month to read differently because this site has an international audience. In the case above I want it to read like this: 2014-Nov-16.
I know this can be done using a RegEx, however, I have no idea how to write this RegEx as I am not good at them. Of course in my example above 11 = Nov, 12 would equal Dec and so on for each month.
Here's a snippets with jQuery and Moment.js that does what you want, I made format into a variable so you can play with is.
$('.release-date').each( function() {
var format = "Do MMM YYYY";
var $this = $( this );
var old_date = $.trim($this.text());
var new_date = moment(old_date , 'YYYY-MM-DD').format( format );
$this.text($this.text().replace(old_date, new_date));
});
<script src="http://momentjs.com/downloads/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="release-date"><i class="fa fa-calendar"></i> 2014-11-16</span>
You can use the Javascript Date to save you some ugly regex
new Date("2014-11-16")
>> Sat Nov 15 2014 16:00:00 GMT-0800 (PST)
new Date("2014-11-16 PST")
>> Sun Nov 16 2014 00:00:00 GMT-0800 (PST)
Unless you add another library like momemt.js or something, you may need to add a little helper to get the month as a string. Something like:
function monthToString(month) {
var months = [ 'Jan', 'Feb', ... , 'Dec' ];
return months[month % months.length]
}
Then you can build the new date string like this
function convertDateString(dateFromCms) {
var date = new Date(dateFromCms);
return date.getFullYear() + "-" + monthToString(date.getMonth()) + "-" + date.getDate();
}
Or something along those lines. Check out the MDN for more about how Date works.
If you want to select the textNode of the span elements, you can iterate through their childNodes and filter the textNode:
[].forEach.call(document.querySelectorAll('.release-date'), function(el) {
var n = el.childNodes, inputDate;
for ( var i = n.length; i--; ) {
if ( n[i].nodeType === 3 && n[i].nodeValue.trim().length ) {
inputDate = n[i].nodeValue.trim();
n[i].nodeValue = // modify the input date
}
}
});
You can do it this way:
Fiddle
var elem = document.getElementsByClassName('release-date')[0];
var text = elem.innerHTML;
var regex = /-(\d{1,2})-/m
var month = regex.exec(text);
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'August', 'Sept', 'Oct', 'Nov', 'Dec']
if (month[1]) {
elem.innerHTML = text.replace(regex, "-" + months[parseInt(month[1], 10) - 1] + "-")
}
This works too..
var months = {
1: 'jan',
2: 'feb',
3: 'march',
4: 'apr',
5: 'may',
6: 'june',
7: 'july',
8: 'aug',
9: 'sep',
10: 'oct',
11: 'nov',
12: 'dec'
};
var currentDate = "2014-11-16"; // your date string would go here. Note, I left the retrieval of it out. This is trivial w/ jQuery... $('.release-date').text();
var redrawnCurrentDate = currentDate.replace(/(\d{2})-(\d{2})$/,function(_,$1,$2){
return months[$1] + "-" + $2;
});
$('.release-date').text(redrawnCurrentDate);
Related
i have two dates Date1 and Date2 in format ("Wed Apr 21 2020") .I want to compare only months from two date strings.Forex ample Date1="Fri Sep 13 2020" and Date2="Sun Feb 21 2020" and now i want to compare September from DATE1 with February from DATE2 in such a way .
if(September>February){
var X=greater
}else{
var X=smaller
}
how can i achieve this in JAVASCRIPT
The easiest way is to extract the month from the string and get its index by using an array. See an example below:
const Date1 = 'Fri Sep 13 2020';
const Date2 = 'Sun Feb 21 2020';
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const getMonthIndex = date => months.indexOf(date.split(' ')[1]);
if (getMonthIndex(Date1) > getMonthIndex(Date2)) {
// var X=greater
console.log('greater');
} else {
// var X=smaller
console.log('smaller');
}
I have a function that I am trying to get to format the date and time or just the date at the moment.
function(){
var d = new Date();
var n = d.getTime();
return 'VZW Dfill - ' + n;}
What I have tried
function(){
var d = new Date();
return 'VZW Dfill - ' + d;}
This returns
VZW Dfill - Thu Jan 30 2020 103924 GMT-0500 (Eastern Standard Time)
I would like the format to be 2020JAN30
I have also tried the following but this does not work
function(){
var d = new Date('YYYYMDD');
return 'VZW Dfill - ' + d;}
The above breaks the function.
Any help is appreciated.
This is actually surprisingly complex using pure JavaScript. Here's one (of many) solutions:
var now = new Date();
var months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
var formattedDate = now.getFullYear() + months[now.getMonth()] + now.getDate();
alert(formattedDate);
Using your code from above, write the following function:
function(){
var d = new Date();
var months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
d = d.getFullYear() + months[d.getMonth()] + d.getDate();
return 'VZW Dfill - ' + d;}
There is a pretty extensive thread about formatting JavaScript dates here. Most of them involve (common) third party packages.
You can use also locale
console.log(today.toLocaleDateString("zh-TW")); // 2020/1/30
I have a date format that is like this
"5-2015"
How can I convert it so that it appears as "May 2015" on screen?
You could try MomentJS http://momentjs.com/ which is a Date/Time library for Javascript. I believe the syntax would be moment(yourDate, 'M-YYYY').format('MMM YYYY');
If you want to roll your own:
function format(date) {
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var month = date.substring(0, date.indexOf('-'));
var year = date.substring(date.indexOf('-') + 1);
return months[parseInt(month) - 1] + ' ' + year;
}
var formatted = format('5-2015');
Assuming all of your dates are in the format of "5-2015" (e.g. 6-2015 or 12-2015), what you can do is use the split function on javascript split the string value into months and years.
For example:
var date = "5-2015";
date.split("-"); //splits the date whenever it sees the dash
var month;
if(date[0] == "5"){ //accesses the first split value (the month value) and check if it's a month.
month = "May";
} //do this with the rest of the months.
var finalString = month + " " + date[1]; //constructs the final string, i.e. May 2015
alert(finalString);
You can go like this:
function parseDate(dateString) {
var d = dateString.split("-"); // ["5", "2015"]
// Month is 0-based, so subtract 1
var D = new Date(d[1], d[0]-1).toString().split(" "); // ["Fri", "May", "01", "2015", "00:00:00", "GMT+0200", "(Central", "Europe", "Daylight", "Time)"]
return D[1] + " " + D[3];
}
(function() {
alert(parseDate("5-2015"));
}());
I have this String :
var str = "Thu, 10 Apr 2014 09:19:08 +0000";
I would like to get this format : "10 Apr 2014"
How can i do that?
var str = "Thu, 10 Apr 2014 09:19:08 +0000";
var d = new Date(str);
var month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var b= d.getDate()+' '+month[d.getMonth()]+' '+d.getFullYear();
alert(b);
Check the result in
JSFiddle
You can split the string on spaces and take the second to the fourth items and join:
var d = str.split(' ').slice(1, 4).join(' ');
Demo: http://jsfiddle.net/Guffa/7FuD6/
you can use the substring() method like this,
var str = "Thu, 10 Apr 2014 09:19:08 +0000";
var res = str.substring(5,15);
var str = "Thu, 10 Apr 2014 09:19:08 +0000",
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
d = new Date(str);
d.getDate() + " " + months[d.getMonth()] + " " + d.getFullYear(); //"10 Apr 2014"
The date string you have can be passed into the Date constructor to get a date object, d. The date object has various methods to that gives day, year, month, time etc. Since months are returned as an integer and we need the name, we use an array called months.
I am getting string data from a Google Calendar feed. The date is already set, by parameter, with the desired timezone.
2014-05-24T07:00:00.000-04:00
I know there are wonderful libraries like moment.js and date.js this will help format my date, but they also work with a Date object, which throws my date into a client's culture. At that point I am then juggling offsets. Would rather avoid that.
Other than a lot of conditional string manipulation, is there a simple way to do this, or I am oversimplifying (again)?
Example:
2014-05-24T07:00:00.000-04:00 to May, 24, 2014 - 7:00 AM
The following short code will parse your date, using the values present, without offsetting by the timezone:
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var res = /(\d+)\-(\d+)\-(\d+)T(\d+)\:(\d+)/
.exec('2014-05-24T07:00:00.000-04:00');
var am = (res[4] < 12);
var date = months[res[2]-1] + ', ' + res[3] + ', ' + res[1];
var time = am ? (parseInt(res[4]) + ':' + res[5] + 'AM') :
(res[4] - 12 + ':' + res[5] + 'PM');
var formatted = date + ' - ' + time;
console.log(formatted);
You can convert this string into a Date object like below,
new Date("2014-05-24T07:00:00.000-04:00")
Then you can easily convert this date object into your desired format by using any of the jQuery libraries such as jquery.globalize.js ...
Here you go:
var d = new Date('2014-05-24T07:00:00.000-04:00');
var calendar = {
months: {
full: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
short: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
days: {
full: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
short: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
}
};
console.log(calendar.months.short[d.getMonth()]+', '+d.getDate()+', '+d.getFullYear());
A simple function to reformat the string is:
function reformatDateString(s) {
s = s.match(/\d+/g);
var months = ['January','February','March','April','May','June','July',
'August','September','October','November','December'];
var ampm = s[3]<12? 'AM':'PM';
return months[--s[1]] + ', ' + +s[2] + ', ' + s[0] + ' - ' +
(s[3]%12 || 12) + ':' + s[4] + ' ' + ampm;
}
console.log(reformatDateString('2014-05-24T07:00:00.000-04:00')); // May, 24, 2014 - 7:00 AM
console.log(reformatDateString('2014-05-24T17:00:00.000-04:00')); // May, 24, 2014 - 5:00 PM
console.log(reformatDateString('2014-05-04T00:20:00.000-04:00')); // May, 4, 2014 - 12:20 AM
Which also assumes that you don't want leading zeros on single digit numbers except for the minutes, as a time like 12:5 PM isn't as readable (to me) as 12:05 PM.
Also you may need to modify the months array, it's not clear in the OP whether you want full month names or abbreviations (Jan, Feb, etc.).