Konwersja ciągu znaków na datę w JavaScript
Jak mogę przekonwertować łańcuch znaków na datę w JavaScript?
var st = "date in some format"
var dt = new date();
var dt_st= //st in date format same as dt
29 answers
Najlepszym formatem łańcuchów do parsowania łańcuchów jest format ISO date wraz z konstruktorem obiektu JavaScript Date.
Przykłady formatu ISO: YYYY-MM-DD
LUB YYYY-MM-DDTHH:MM:SS
.
Ale czekaj! samo użycie "formatu ISO" nie działa niezawodnie samo w sobie. String są czasami przetwarzane jako UTC, a czasami jako localtime(w zależności od dostawcy przeglądarki i wersji). Najlepszą praktyką powinno być zawsze przechowywanie dat jako UTC i wykonywanie obliczeń jako UTC.
Aby przeanalizować datę jako UTC, dołącz a Z - np.: new Date('2011-04-11T10:20:30Z')
.
Aby wyświetlić datę w UTC, użyj .toUTCString()
,
aby wyświetlić datę w czasie lokalnym użytkownika, Użyj .toString()
.
Więcej informacji na temat MDN / Date i tej odpowiedzi.
Dla starej zgodności z Internet Explorerem (wersje poniżej 9 nie obsługują formatu ISO w Konstruktorze daty), należy podzielić reprezentację łańcucha DateTime na jego części, a następnie użyć konstruktora używając części datetime, np.: new Date('2011', '04' - 1, '11', '11', '51', '00')
. Należy pamiętać, że liczba miesiąc musi być o 1 mniej.
Alternatywna metoda-użyj odpowiedniej biblioteki:
Możesz również skorzystać z biblioteki Moment.js, który pozwala na parsowanie daty z określoną strefą czasową.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:34:51
Niestety dowiedziałem się, że
var mydate = new Date('2014-04-03');
console.log(mydate.toDateString());
Zwraca "Śr Kwi 02 2014". Wiem, że to brzmi szalenie, ale zdarza się to dla niektórych użytkowników.
Rozwiązanie kuloodporne jest następujące:
var parts ='2014-04-03'.split('-');
// Please pay attention to the month (parts[1]); JavaScript counts months from 0:
// January - 0, February - 1, etc.
var mydate = new Date(parts[0], parts[1] - 1, parts[2]);
console.log(mydate.toDateString());
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-17 15:25:10
var st = "26.04.2013";
var pattern = /(\d{2})\.(\d{2})\.(\d{4})/;
var dt = new Date(st.replace(pattern,'$3-$2-$1'));
I wyjście będzie:
dt => Date {Fri Apr 26 2013}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-04 05:20:53
function stringToDate(_date,_format,_delimiter)
{
var formatLowerCase=_format.toLowerCase();
var formatItems=formatLowerCase.split(_delimiter);
var dateItems=_date.split(_delimiter);
var monthIndex=formatItems.indexOf("mm");
var dayIndex=formatItems.indexOf("dd");
var yearIndex=formatItems.indexOf("yyyy");
var month=parseInt(dateItems[monthIndex]);
month-=1;
var formatedDate = new Date(dateItems[yearIndex],month,dateItems[dayIndex]);
return formatedDate;
}
stringToDate("17/9/2014","dd/MM/yyyy","/");
stringToDate("9/17/2014","mm/dd/yyyy","/")
stringToDate("9-17-2014","mm-dd-yyyy","-")
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-21 17:28:21
Podaj jako argument do Date ():
var st = "date in some format"
var dt = new Date(st);
Możesz uzyskać dostęp do daty, miesiąca, roku, używając na przykład: dt.getMonth()
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-11 09:26:13
new Date(2000, 10, 1)
da ci "śro lis 01 2000 00: 00: 00 GMT + 0100 (CET)"
Zobacz, że 0 za miesiąc daje Ci Styczeń
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-11 09:25:53
Jeśli możesz użyć biblioteki terrific moment (np. w węźle.js project) możesz łatwo przeanalizować datę używając np.
var momentDate = moment("2014-09-15 09:00:00");
I może uzyskać dostęp do obiektu JS date poprzez
momentDate ().toDate();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-22 09:08:52
Moment.js ( http://momentjs.com/) jest kompletnym i dobrym pakietem do użycia i obsługuje ISO 8601 strings.
Można dodać datę i format łańcucha znaków.
moment("12-25-1995", "MM-DD-YYYY");
I możesz sprawdzić, czy data jest ważna.
moment("not a real date").isValid(); //Returns false
Zobacz dokumentację http://momentjs.com/docs/#/parsing/string-format/
Rekomendacja: zalecam użycie pakietu dla dat, który zawiera wiele formatów, ponieważ strefa czasowa i czas formatowania zarządzanie jest naprawdę duży problem, moment js rozwiązać wiele formatów. Mógłbyś łatwo analizować datę od prostego ciągu do daty, ale myślę, że jest to ciężka praca w celu obsługi wszystkich formatów i odmian dat.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-24 16:21:27
Dla tych, którzy szukają małego i inteligentnego rozwiązania:
String.prototype.toDate = function(format)
{
var normalized = this.replace(/[^a-zA-Z0-9]/g, '-');
var normalizedFormat= format.toLowerCase().replace(/[^a-zA-Z0-9]/g, '-');
var formatItems = normalizedFormat.split('-');
var dateItems = normalized.split('-');
var monthIndex = formatItems.indexOf("mm");
var dayIndex = formatItems.indexOf("dd");
var yearIndex = formatItems.indexOf("yyyy");
var hourIndex = formatItems.indexOf("hh");
var minutesIndex = formatItems.indexOf("ii");
var secondsIndex = formatItems.indexOf("ss");
var today = new Date();
var year = yearIndex>-1 ? dateItems[yearIndex] : today.getFullYear();
var month = monthIndex>-1 ? dateItems[monthIndex]-1 : today.getMonth()-1;
var day = dayIndex>-1 ? dateItems[dayIndex] : today.getDate();
var hour = hourIndex>-1 ? dateItems[hourIndex] : today.getHours();
var minute = minutesIndex>-1 ? dateItems[minutesIndex] : today.getMinutes();
var second = secondsIndex>-1 ? dateItems[secondsIndex] : today.getSeconds();
return new Date(year,month,day,hour,minute,second);
};
Przykład:
"22/03/2016 14:03:01".toDate("dd/mm/yyyy hh:ii:ss");
"2016-03-29 18:30:00".toDate("yyyy-mm-dd hh:ii:ss");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-26 17:05:30
Jeśli chcesz przekonwertować z formatu "dd / MM / RRRR". Oto przykład:
var pattern = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var arrayDate = stringDate.match(pattern);
var dt = new Date(arrayDate[3], arrayDate[2] - 1, arrayDate[1]);
To rozwiązanie działa w wersjach IE mniej niż 9.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-29 02:03:55
Znaczniki czasu powinny być przypisane do liczby
var ts = '1471793029764';
ts = Number(ts); // cast it to a Number
var date = new Date(ts); // works
var invalidDate = new Date('1471793029764'); // does not work. Invalid Date
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-21 15:42:34
Date.parse
prawie dostaniesz to, czego chcesz. Dławi się na am
/pm
CZĘŚĆ, ALE z jakimś hackingiem można to zrobić:
var str = 'Sun Apr 25, 2010 3:30pm',
timestamp;
timestamp = Date.parse(str.replace(/[ap]m$/i, ''));
if(str.match(/pm$/i) >= 0) {
timestamp += 12 * 60 * 60 * 1000;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-11 09:30:42
Sprawdź bibliotekę datejs http://www.datejs.com/
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-11 09:22:54
Just new Date(st);
Zakładając, że jest to właściwy format.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-11 09:23:08
Konwertuj do formatu pt-BR:
var dateString = "13/10/2014";
var dataSplit = dateString.split('/');
var dateConverted;
if (dataSplit[2].split(" ").length > 1) {
var hora = dataSplit[2].split(" ")[1].split(':');
dataSplit[2] = dataSplit[2].split(" ")[0];
dateConverted = new Date(dataSplit[2], dataSplit[1]-1, dataSplit[0], hora[0], hora[1]);
} else {
dateConverted = new Date(dataSplit[2], dataSplit[1] - 1, dataSplit[0]);
}
Mam nadzieję, że komuś pomożesz!!!Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-13 18:11:09
Stworzyłem do tego fiddle, możesz użyć funkcji toDate () na dowolnym łańcuchu daty i podać format daty. Spowoduje to zwrócenie obiektu daty. https://jsfiddle.net/Sushil231088/q56yd0rp/
"17/9/2014".toDate("dd/MM/yyyy", "/")
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-23 14:18:48
Do konwersji string to date w js używam http://momentjs.com/
moment().format('MMMM Do YYYY, h:mm:ss a'); // August 16th 2015, 4:17:24 pm
moment().format('dddd'); // Sunday
moment().format("MMM Do YY"); // Aug 16th 15
moment().format('YYYY [escaped] YYYY'); // 2015 escaped 2015
moment("20111031", "YYYYMMDD").fromNow(); // 4 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 3 years ago
moment().startOf('day').fromNow(); // 16 hours ago
moment().endOf('day').fromNow(); // in 8 hours
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-16 13:17:47
Yet another way to do it:
String.prototype.toDate = function(format) {
format = format || "dmy";
var separator = this.match(/[^0-9]/)[0];
var components = this.split(separator);
var day, month, year;
for (var key in format) {
var fmt_value = format[key];
var value = components[key];
switch (fmt_value) {
case "d":
day = parseInt(value);
break;
case "m":
month = parseInt(value)-1;
break;
case "y":
year = parseInt(value);
}
}
return new Date(year, month, day);
};
a = "3/2/2017";
console.log(a.toDate("dmy"));
// Date 2017-02-03T00:00:00.000Z
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-03 05:11:48
Zrobiłem tę funkcję, aby przekonwertować dowolny obiekt daty NA obiekt daty UTC.
function dateToUTC(date) {
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}
dateToUTC(new Date());
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-07 23:24:29
var date = new Date(year, month, day);
Lub
var date = new Date('01/01/1970');
Łańcuch daty w formacie '01-01-1970' nie będzie działał w Firefoksie, więc lepiej użyj " / "zamiast" - " w łańcuchu formatu daty.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-17 11:20:53
Jeśli musisz sprawdzić zawartość łańcucha przed konwersją na format daty:
// Convert 'M/D/YY' to Date()
mdyToDate = function(mdy) {
var d = mdy.split(/[\/\-\.]/, 3);
if (d.length != 3) return null;
// Check if date is valid
var mon = parseInt(d[0]),
day = parseInt(d[1]),
year= parseInt(d[2]);
if (d[2].length == 2) year += 2000;
if (day <= 31 && mon <= 12 && year >= 2015)
return new Date(year, mon - 1, day);
return null;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-13 03:49:49
var a = "13:15"
var b = toDate(a, "h:m")
alert(b);
function toDate(dStr, format) {
var now = new Date();
if (format == "h:m") {
now.setHours(dStr.substr(0, dStr.indexOf(":")));
now.setMinutes(dStr.substr(dStr.indexOf(":") + 1));
now.setSeconds(0);
return now;
} else
return "Invalid Format";
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-26 16:56:12
ISO 8601-esque datestrings, tak doskonałe jak standard jest, nadal nie są szeroko obsługiwane.
Jest to świetny zasób, aby dowiedzieć się, którego formatu datestring należy użyć:
Http://dygraphs.com/date-formats.html
Tak, to oznacza, że datestring może być tak proste, jak w przeciwieństwie do
"2014/10/13 23:57:52"
zamiast
"2014-10-13 23:57:52"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-14 02:28:30
//little bit of code for Converting dates
var dat1 = document.getElementById('inputDate').value;
var date1 = new Date(dat1)//converts string to date object
alert(date1);
var dat2 = document.getElementById('inputFinishDate').value;
var date2 = new Date(dat2)
alert(date2);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-12 14:34:20
Użyj tego kodu: (mój problem został rozwiązany z tym kodem)
function dateDiff(date1, date2){
var diff = {} // Initialisation du retour
var tmp = date2 - date1;
tmp = Math.floor(tmp/1000); // Nombre de secondes entre les 2 dates
diff.sec = tmp % 60; // Extraction du nombre de secondes
tmp = Math.floor((tmp-diff.sec)/60); // Nombre de minutes (partie entière)
diff.min = tmp % 60; // Extraction du nombre de minutes
tmp = Math.floor((tmp-diff.min)/60); // Nombre d'heures (entières)
diff.hour = tmp % 24; // Extraction du nombre d'heures
tmp = Math.floor((tmp-diff.hour)/24); // Nombre de jours restants
diff.day = tmp;
return diff;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-01 06:26:31
Stworzyłem funkcję parseDateTime do konwersji obiektu string na date i działa we wszystkich przeglądarkach (w tym przeglądarce IE), sprawdź czy ktoś jest wymagany, reference https://github.com/Umesh-Markande/Parse-String-to-Date-in-all-browser
function parseDateTime(datetime) {
var monthNames = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
if(datetime.split(' ').length == 3){
var date = datetime.split(' ')[0];
var time = datetime.split(' ')[1].replace('.00','');
var timearray = time.split(':');
var hours = parseInt(time.split(':')[0]);
var format = datetime.split(' ')[2];
var bits = date.split(/\D/);
date = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
if ((format === 'PM' || format === 'pm') && hours !== 12) {
hours += 12;
try{ time = hours+':'+timearray[1]+':'+timearray[2] }catch(e){ time = hours+':'+timearray[1] }
}
var formateddatetime = new Date(monthNames[monthIndex] + ' ' + day + ' ' + year + ' ' + time);
return formateddatetime;
}else if(datetime.split(' ').length == 2){
var date = datetime.split(' ')[0];
var time = datetime.split(' ')[1];
var bits = date.split(/\D/);
var datetimevalue = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
var day = datetimevalue.getDate();
var monthIndex = datetimevalue.getMonth();
var year = datetimevalue.getFullYear();
var formateddatetime = new Date(monthNames[monthIndex] + ' ' + day + ' ' + year + ' ' + time);
return formateddatetime;
}else if(datetime != ''){
var bits = datetime.split(/\D/);
var date = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
return date;
}
return datetime;
}
var date1 = '2018-05-14 05:04:22 AM'; // yyyy-mm-dd hh:mm:ss A
var date2 = '2018/05/14 05:04:22 AM'; // yyyy/mm/dd hh:mm:ss A
var date3 = '2018/05/04'; // yyyy/mm/dd
var date4 = '2018-05-04'; // yyyy-mm-dd
var date5 = '2018-05-14 15:04:22'; // yyyy-mm-dd HH:mm:ss
var date6 = '2018/05/14 14:04:22'; // yyyy/mm/dd HH:mm:ss
console.log(parseDateTime(date1))
console.log(parseDateTime(date2))
console.log(parseDateTime(date3))
console.log(parseDateTime(date4))
console.log(parseDateTime(date5))
console.log(parseDateTime(date6))
**Output---**
Mon May 14 2018 05:04:22 GMT+0530 (India Standard Time)
Mon May 14 2018 05:04:22 GMT+0530 (India Standard Time)
Fri May 04 2018 00:00:00 GMT+0530 (India Standard Time)
Fri May 04 2018 00:00:00 GMT+0530 (India Standard Time)
Mon May 14 2018 15:04:22 GMT+0530 (India Standard Time)
Mon May 14 2018 14:04:22 GMT+0530 (India Standard Time)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-26 15:35:32
Możesz użyć regex, aby przetworzyć łańcuch do szczegółowego czasu, a następnie utworzyć datę lub dowolny format powrotu, taki jak:
//example : let dateString = "2018-08-17 01:02:03.4"
function strToDate(dateString){
let reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}).(\d{1})/
, [,year, month, day, hours, minutes, seconds, miliseconds] = reggie.exec(dateString)
, dateObject = new Date(year, month-1, day, hours, minutes, seconds, miliseconds);
return dateObject;
}
alert(strToDate(dateString));
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-17 04:28:37
Użyj tego formatu....
//get current date in javascript
var currentDate=New Date();
// for getting a date from a textbox as string format
var newDate=document.getElementById("<%=textBox1.ClientID%>").value;
// convert this date to date time
var MyDate=New Date(newDate);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-30 15:47:18
Możesz także: mydate.toLocaleDateString ();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-25 21:14:50