Подтвердить что ты не робот

JavaScript new Date Ordinal (st, nd, rd, th)

Если это вообще возможно, без библиотек JavaScript или большого количества неуклюжего кода, я ищу самый простой способ форматирования даты через две недели в следующем формате:

13th March 2013

Код, который я использую:

var newdate = new Date(+new Date + 12096e5);
document.body.innerHTML = newdate;

который возвращает дату и время через две недели, но примерно так: ср 27 мар 2013 21:50:29 GMT + 0000 (стандартное время GMT)

Вот код в jsFiddle.

Любая помощь будет оценена!

4b9b3361

Ответ 1

Здесь:

JSFiddle

const nth = function(d) {
  if (d > 3 && d < 21) return 'th';
  switch (d % 10) {
    case 1:  return "st";
    case 2:  return "nd";
    case 3:  return "rd";
    default: return "th";
  }
}
const fortnightAway = new Date(+new Date + 12096e5);
const date = fortnightAway.getDate();
const month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][fortnightAway.getMonth()];

document.getElementById("date").innerHTML = '${date}<sup>${nth(date)}</sup> ${month} ${fortnightAway.getFullYear()}';
sup {
  font-size: x-small
}
<span id="date"></span>

Ответ 2

Вот один лайнер, вдохновленный другими ответами. Он проверяется и будет принимать 0 и отрицательные числа.

function getOrdinalNum(n) {
  return n + (n > 0 ? ['th', 'st', 'nd', 'rd'][(n > 3 && n < 21) || n % 10 > 3 ? 0 : n % 10] : '');
}

Ответ 3

Множество ответов на форматирование, поэтому я буду работать только с n-м целым числом -

Number.prototype.nth= function(){
    if(this%1) return this;
    var s= this%100;
    if(s>3 && s<21) return this+'th';
    switch(s%10){
        case 1: return this+'st';
        case 2: return this+'nd';
        case 3: return this+'rd';
        default: return this+'th';
    }
}

Ответ 4

Я делал это и для дат, но потому, что день месяца может быть только между 1 и 31, я закончил с упрощенным решением.

function dateOrdinal(dom) {
    if (dom == 31 || dom == 21 || dom == 1) return dom + "st";
    else if (dom == 22 || dom == 2) return dom + "nd";
    else if (dom == 23 || dom == 3) return dom + "rd";
    else return dom + "th";
};

или компактная версия с использованием условных операторов

function dateOrdinal(d) {
    return d+(31==d||21==d||1==d?"st":22==d||2==d?"nd":23==d||3==d?"rd":"th")
};

http://jsben.ch/#/DrBpl

Ответ 5

Множество ответов, здесь другое:

function addOrd(n) {
  var ords = [,'st','nd','rd'];
  var ord, m = n%100;
  return n + ((m > 10 && m < 14)? 'th' : ords[m%10] || 'th');
}

// Return date string two weeks from now (14 days) in 
// format 13th March 2013
function formatDatePlusTwoWeeks(d) {
  var months = ['January','February','March','April','May','June',
                'July','August','September','October','November','December'];

  // Copy date object so don't modify original
  var e = new Date(d);

  // Add two weeks (14 days)
  e.setDate(e.getDate() + 14);
  return addOrd(e.getDate()) + ' ' + months[e.getMonth()] + ' ' + e.getFullYear();
}

alert(formatDatePlusTwoWeeks(new Date(2013,2,13))); // 27th March 2013

Ответ 6

Я немного опаздываю на вечеринку, но это должно сработать:

function ordinal(number) {
  number = Number(number)
  if(!number || (Math.round(number) !== number)) {
    return number
  }
  var signal = (number < 20) ? number : Number(('' + number).slice(-1))
  switch(signal) {
    case 1:
      return number + 'st'
    case 2:
      return number + 'nd'
    case 3:
      return number + 'rd'
    default:
      return number + 'th'
  }
}

function specialFormat(date) {
  // add two weeks
  date = new Date(+date + 12096e5)
  var months = [
    'January'
    , 'February'
    , 'March'
    , 'April'
    , 'May'
    , 'June'
    , 'July'
    , 'August'
    , 'September'
    , 'October'
    , 'November'
    , 'December'
  ]
  var formatted = ordinal(date.getDate())
  formatted += ' ' + months[date.getMonth()]
  return formatted + ' ' + date.getFullYear()
}

document.body.innerHTML = specialFormat(new Date())

Ответ 7

Как уже упоминалось, вот еще один ответ.

Это напрямую зависит от ответа @kennebec, который я нашел наиболее простой способ получить эту дату Ordinal, сгенерированную для данной даты JavaScript:

Я создал два prototype function следующим образом:

Date.prototype.getDateWithDateOrdinal = function() {
    var d = this.getDate();  // from here on I've used Kennebec answer, but improved it.
    if(d>3 && d<21) return d+'th';
    switch (d % 10) {
        case 1:  return d+"st";
        case 2:  return d+"nd";
        case 3:  return d+"rd";
        default: return d+"th";
    }
};

Date.prototype.getMonthName = function(shorten) {
    var monthsNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    var monthIndex = this.getMonth();
    var tempIndex = -1;
    if (monthIndex == 0){ tempIndex = 0 };
    if (monthIndex == 1){ tempIndex = 1 };
    if (monthIndex == 2){ tempIndex = 2 };
    if (monthIndex == 3){ tempIndex = 3 };
    if (monthIndex == 4){ tempIndex = 4 };
    if (monthIndex == 5){ tempIndex = 5 };
    if (monthIndex == 6){ tempIndex = 6 };
    if (monthIndex == 7){ tempIndex = 7 };
    if (monthIndex == 8){ tempIndex = 8 };
    if (monthIndex == 9){ tempIndex = 9 };
    if (monthIndex == 10){ tempIndex = 10 };
    if (monthIndex == 11){ tempIndex = 11 };

    if (tempIndex > -1) {
        this.monthName = (shorten) ? monthsNames[tempIndex].substring(0, 3) : monthsNames[tempIndex];
    } else {
        this.monthName = "";
    }

    return this.monthName;
};

Примечание. просто включите указанные выше функции prototype в свой JS Script и используйте его, как описано ниже.

И всякий раз, когда есть JS date, мне нужно сгенерировать дату с порядком даты. Я использую этот метод прототипа следующим образом: JS date:

var myDate = new Date();
// You may have to check your JS Console in the web browser to see the following
console.log("date with date ordinal: "+myDate.getDateWithDateOrdinal()+" "+myDate.getMonthName()+" "+myDate.getFullYear());

// or I will update the Div. using jQuery
$('#date').html("date with date ordinal: "+myDate.getDateWithDateOrdinal()+" "+myDate.getMonthName()+" "+myDate.getFullYear());

И он будет печатать дату с порядковым номером даты, как показано в следующем live demo:

	Date.prototype.getMonthName = function(shorten) {
		var monthsNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
		var monthIndex = this.getMonth();
		var tempIndex = -1;
	    if (monthIndex == 0){ tempIndex = 0 };
	    if (monthIndex == 1){ tempIndex = 1 };
	    if (monthIndex == 2){ tempIndex = 2 };
	    if (monthIndex == 3){ tempIndex = 3 };
	    if (monthIndex == 4){ tempIndex = 4 };
	    if (monthIndex == 5){ tempIndex = 5 };
	    if (monthIndex == 6){ tempIndex = 6 };
	    if (monthIndex == 7){ tempIndex = 7 };
	    if (monthIndex == 8){ tempIndex = 8 };
	    if (monthIndex == 9){ tempIndex = 9 };
	    if (monthIndex == 10){ tempIndex = 10 };
	    if (monthIndex == 11){ tempIndex = 11 };

	    if (tempIndex > -1) {
			this.monthName = (shorten) ? monthsNames[tempIndex].substring(0, 3) : monthsNames[tempIndex];
	    } else {
	    	this.monthName = "";
	    }

	    return this.monthName;
	};

    Date.prototype.getDateWithDateOrdinal = function() {
		var d = this.getDate();  // from here on I've used Kennebec answer, but improved it.
	    if(d>3 && d<21) return d+'th';
	    switch (d % 10) {
            case 1:  return d+"st";
            case 2:  return d+"nd";
            case 3:  return d+"rd";
            default: return d+"th";
        }
	};

	var myDate = new Date();
    // You may have to check your JS Console in the web browser to see the following
	console.log("date with date ordinal: "+myDate.getDateWithDateOrdinal()+" "+myDate.getMonthName()+" "+myDate.getFullYear());
    
    // or I will update the Div. using jQuery
    $('#date').html("date with date ordinal: "+myDate.getDateWithDateOrdinal()+" "+myDate.getMonthName()+" "+myDate.getFullYear());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="date"></p>

Ответ 8

Кратное и компактное решение:

function format(date, tmp){
  return [
    (tmp = date.getDate()) + 
      ([, 'st', 'nd', 'rd'][/1?.$/.exec(tmp)] || 'th'),
    [ 'January', 'February', 'March', 'April',
      'May', 'June', 'July', 'August',
      'September', 'October', 'November', 'December'
    ][date.getMonth()],
    date.getFullYear()
  ].join(' ')
}


// 14 days from today

console.log('14 days from today: ' + 
  format(new Date(+new Date + 14 * 864e5)));

// test formatting for all dates within a month from today

var day = 864e5, today = +new Date;
for(var i = 0; i < 32; i++) {
  console.log('Today + ' + i + ': ' + format(new Date(today + i * day)))
}

Ответ 9

	Date.prototype.getMonthName = function(shorten) {
		var monthsNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
		var monthIndex = this.getMonth();
		var tempIndex = -1;
	    if (monthIndex == 0){ tempIndex = 0 };
	    if (monthIndex == 1){ tempIndex = 1 };
	    if (monthIndex == 2){ tempIndex = 2 };
	    if (monthIndex == 3){ tempIndex = 3 };
	    if (monthIndex == 4){ tempIndex = 4 };
	    if (monthIndex == 5){ tempIndex = 5 };
	    if (monthIndex == 6){ tempIndex = 6 };
	    if (monthIndex == 7){ tempIndex = 7 };
	    if (monthIndex == 8){ tempIndex = 8 };
	    if (monthIndex == 9){ tempIndex = 9 };
	    if (monthIndex == 10){ tempIndex = 10 };
	    if (monthIndex == 11){ tempIndex = 11 };

	    if (tempIndex > -1) {
			this.monthName = (shorten) ? monthsNames[tempIndex].substring(0, 3) : monthsNames[tempIndex];
	    } else {
	    	this.monthName = "";
	    }

	    return this.monthName;
	};

    Date.prototype.getDateWithDateOrdinal = function() {
		var d = this.getDate();  // from here on I've used Kennebec answer, but improved it.
	    if(d>3 && d<21) return d+'th';
	    switch (d % 10) {
            case 1:  return d+"st";
            case 2:  return d+"nd";
            case 3:  return d+"rd";
            default: return d+"th";
        }
	};

	var myDate = new Date();
    // You may have to check your JS Console in the web browser to see the following
	console.log("date with date ordinal: "+myDate.getDateWithDateOrdinal()+" "+myDate.getMonthName()+" "+myDate.getFullYear());
    
    // or I will update the Div. using jQuery
    $('#date').html("date with date ordinal: "+myDate.getDateWithDateOrdinal()+" "+myDate.getMonthName()+" "+myDate.getFullYear());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="date"></p>

Ответ 10

function getSuffixForDate(day) {
  const lastNumberOfTheDay = day[day.length];

  const suffixes = {
    1: () => 'st',
    21: () => 'st',
    31: () => 'st',
    2: () => 'nd',
    22: () => 'nd',
    3: () => 'rd',
    23: () => 'rd',
  };

  return suffixes[lastNumberOfTheDay] !== undefined ? '${day}${suffixes[lastNumberOfTheDay]()}' : '${day}th';
}

const date = new Date();
const formattedDate = '${getSuffixForDate(date.getDate())} ${monthNames[date.getMonth()]} ${date.getFullYear()}';

Человекочитаемая версия...

Ответ 11

Супер простая функциональная реализация:

const ordinal = (d) => {
  const nth = { '1': 'st', '2': 'nd', '3': 'rd' }
  return `${d}${nth[d] || 'th'}`
}

const monthNames = ['January','February','March','April','May','June','July','August','September','October','November','December']

const dateString = (date) => `${ordinal(date.getDate())} ${monthNames[date.getMonth()]} ${date.getFullYear()}`

// Use like this: 
dateString(new Date()) // 18th July 2016

Ответ 12

Сильно вдохновлено @user2309185.

const ordinal = (d) => {
  return d + (['st', 'nd', 'rd'][d % 10 - 1] || 'th')
}

Ответ 13

Вот простое решение:

var date = today.getDate() + (today.getDate() % 10 == 1 && today.getDate() != 11 ? + 'st': (today.getDate() % 10 == 2 && today.getDate() != 12 ? + 'nd': 

(today.getDate() % 10 == 3 && today.getDate() != 13 ? + 'rd':'th')));