Date class conversion - javascript

I have next code to take date:
var d = new Date();
var n = d.toString();
with output: Sun Oct 15 2017 12:09:42 GMT+0300 (EEST)
But I need to convert it to next format: 2017-10-15 12:09:42 +0300
Is that possible to do with Date class methods or I should use some regex for output string, to format it?

This can be done easily with a library called moment.js, please go through the docs for any additional tweaks, please check my below example and let me know if this helps you!
var moment_d = moment().format('YYYY-MM-DD hh:mm:ss ZZ');
console.log(moment_d);
<script src="https://momentjs.com/downloads/moment.min.js"></script>

There is nothing in JavaScript's Date object that will conveniently get you the desired output. On the other hand, moment.js is a 80+ KB beast which is clearly an overkill in most situations.
There are some lightweight solutions out there if you look for them.
Alternatively you could parse the output of .toISOString(), which gets you as far as '2017-10-15T12:09:42.301Z', and combine it with .getTimezoneOffset() which returns the number of minutes from the UTC (positive towards West).
JS date-time manipulation libraries being large as they are, I recommend rolling your own if you only need to cover a few cases.

function formatDate(date) {
date = date || new Date(); // default to current time if parameter is not supplied
let formattedDate = date.toISOString(); // returns 2000-01-04T00:00:00.000Z
const timezone = date.getTimezoneOffset() / 0.6; // returns timezone in minutes, so dividing by 0.6 gives us e.g -100 for -1hr
const timezoneString = String(timezone) // padStart is a method on String
.padStart(4, '0') // add zeroes to the beginning if only 1 digits
.replace(/^(-|\+)(\d{3})$/, '$10$2') // add a zero between a - or + and the first digit if needed
.replace(/^\d/, '+$&'); // add a plus to the beginning if zero timezone difference
formattedDate = formattedDate
.replace('T', ' ') // replace the T with a space
.replace(/\.\d{3}Z/, '') // remove the Z and milliseconds
+ ' ' // add a space between timezone and time
+ timezoneString; // append timezone
return formattedDate;
}
console.log(formatDate(new Date(2016, 08, 24, 9, 20, 0)));
console.log(formatDate(new Date(2015, 03, 9, 18, 4, 30)));
console.log(formatDate(new Date(1999, 12, 4)));
console.log(formatDate(new Date(1999, 01, 4)));
console.log('----');

Related

Better way to get the current date for the input type "date" as a default value? [duplicate]

I have a date with the format Sun May 11,2014. How can I convert it to 2014-05-11 using JavaScript?
function taskDate(dateMilli) {
var d = (new Date(dateMilli) + '').split(' ');
d[2] = d[2] + ',';
return [d[0], d[1], d[2], d[3]].join(' ');
}
var datemilli = Date.parse('Sun May 11,2014');
console.log(taskDate(datemilli));
The code above gives me the same date format, sun may 11,2014. How can I fix this?
Just leverage the built-in toISOString method that brings your date to the ISO 8601 format:
let yourDate = new Date()
yourDate.toISOString().split('T')[0]
Where yourDate is your date object.
Edit: #exbuddha wrote this to handle time zone in the comments:
const offset = yourDate.getTimezoneOffset()
yourDate = new Date(yourDate.getTime() - (offset*60*1000))
return yourDate.toISOString().split('T')[0]
You can do:
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
console.log(formatDate('Sun May 11,2014'));
Usage example:
console.log(formatDate('Sun May 11,2014'));
Output:
2014-05-11
Demo on JSFiddle: http://jsfiddle.net/abdulrauf6182012/2Frm3/
I use this way to get the date in format yyyy-mm-dd :)
var todayDate = new Date().toISOString().slice(0, 10);
console.log(todayDate);
2020 ANSWER
You can use the native .toLocaleDateString() function which supports several useful params like locale (to select a format like MM/DD/YYYY or YYYY/MM/DD), timezone (to convert the date) and formats details options (eg: 1 vs 01 vs January).
Examples
const testCases = [
new Date().toLocaleDateString(), // 8/19/2020
new Date().toLocaleString(undefined, {year: 'numeric', month: '2-digit', day: '2-digit', weekday:"long", hour: '2-digit', hour12: false, minute:'2-digit', second:'2-digit'}),
new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}), // 08/19/2020 (month and day with two digits)
new Date().toLocaleDateString('en-ZA'), // 2020/08/19 (year/month/day) notice the different locale
new Date().toLocaleDateString('en-CA'), // 2020-08-19 (year-month-day) notice the different locale
new Date().toLocaleString("en-US", {timeZone: "America/New_York"}), // 8/19/2020, 9:29:51 AM. (date and time in a specific timezone)
new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"}), // 09 (just the hour)
]
for (const testData of testCases) {
console.log(testData)
}
Notice that sometimes to output a date in your specific desire format, you have to find a compatible locale with that format.
You can find the locale examples here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all
Please notice that locale just change the format, if you want to transform a specific date to a specific country or city time equivalent then you need to use the timezone param.
The simplest way to convert your date to the yyyy-mm-dd format, is to do this:
var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
.toISOString()
.split("T")[0];
How it works:
new Date("Sun May 11,2014") converts the string "Sun May 11,2014" to a date object that represents the time Sun May 11 2014 00:00:00 in a timezone based on current locale (host system settings)
new Date(date.getTime() - (date.getTimezoneOffset() * 60000 )) converts your date to a date object that corresponds with the time Sun May 11 2014 00:00:00 in UTC (standard time) by subtracting the time zone offset
.toISOString() converts the date object to an ISO 8601 string 2014-05-11T00:00:00.000Z
.split("T") splits the string to array ["2014-05-11", "00:00:00.000Z"]
[0] takes the first element of that array
Demo
var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
.toISOString()
.split("T")[0];
console.log(dateString);
Note :
The first part of the code (new Date(...)) may need to be tweaked a bit if your input format is different from that of the OP. As mikeypie
pointed out in the comments, if the date string is already in the expected output format and the local timezone is west of UTC, then new Date('2022-05-18') results in 2022-05-17. And a user's locale (eg. MM/DD/YYYY vs DD-MM-YYYY) may also impact how a date is parsed by new Date(...). So do some proper testing if you want to use this code for different input formats.
A combination of some of the answers:
var d = new Date(date);
date = [
d.getFullYear(),
('0' + (d.getMonth() + 1)).slice(-2),
('0' + d.getDate()).slice(-2)
].join('-');
format = function date2str(x, y) {
var z = {
M: x.getMonth() + 1,
d: x.getDate(),
h: x.getHours(),
m: x.getMinutes(),
s: x.getSeconds()
};
y = y.replace(/(M+|d+|h+|m+|s+)/g, function(v) {
return ((v.length > 1 ? "0" : "") + z[v.slice(-1)]).slice(-2)
});
return y.replace(/(y+)/g, function(v) {
return x.getFullYear().toString().slice(-v.length)
});
}
Result:
format(new Date('Sun May 11,2014'), 'yyyy-MM-dd')
"2014-05-11
If you don't have anything against using libraries, you could just use the Moments.js library like so:
var now = new Date();
var dateString = moment(now).format('YYYY-MM-DD');
var dateStringWithTime = moment(now).format('YYYY-MM-DD HH:mm:ss');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
You can use toLocaleDateString('fr-CA') on Date object
console.log(new Date('Sun May 11,2014').toLocaleDateString('fr-CA'));
Also I found out that those locales give right result from this locales list List of All Locales and Their Short Codes?
'en-CA'
'fr-CA'
'lt-LT'
'sv-FI'
'sv-SE'
var localesList = ["af-ZA",
"am-ET",
"ar-AE",
"ar-BH",
"ar-DZ",
"ar-EG",
"ar-IQ",
"ar-JO",
"ar-KW",
"ar-LB",
"ar-LY",
"ar-MA",
"arn-CL",
"ar-OM",
"ar-QA",
"ar-SA",
"ar-SY",
"ar-TN",
"ar-YE",
"as-IN",
"az-Cyrl-AZ",
"az-Latn-AZ",
"ba-RU",
"be-BY",
"bg-BG",
"bn-BD",
"bn-IN",
"bo-CN",
"br-FR",
"bs-Cyrl-BA",
"bs-Latn-BA",
"ca-ES",
"co-FR",
"cs-CZ",
"cy-GB",
"da-DK",
"de-AT",
"de-CH",
"de-DE",
"de-LI",
"de-LU",
"dsb-DE",
"dv-MV",
"el-GR",
"en-029",
"en-AU",
"en-BZ",
"en-CA",
"en-GB",
"en-IE",
"en-IN",
"en-JM",
"en-MY",
"en-NZ",
"en-PH",
"en-SG",
"en-TT",
"en-US",
"en-ZA",
"en-ZW",
"es-AR",
"es-BO",
"es-CL",
"es-CO",
"es-CR",
"es-DO",
"es-EC",
"es-ES",
"es-GT",
"es-HN",
"es-MX",
"es-NI",
"es-PA",
"es-PE",
"es-PR",
"es-PY",
"es-SV",
"es-US",
"es-UY",
"es-VE",
"et-EE",
"eu-ES",
"fa-IR",
"fi-FI",
"fil-PH",
"fo-FO",
"fr-BE",
"fr-CA",
"fr-CH",
"fr-FR",
"fr-LU",
"fr-MC",
"fy-NL",
"ga-IE",
"gd-GB",
"gl-ES",
"gsw-FR",
"gu-IN",
"ha-Latn-NG",
"he-IL",
"hi-IN",
"hr-BA",
"hr-HR",
"hsb-DE",
"hu-HU",
"hy-AM",
"id-ID",
"ig-NG",
"ii-CN",
"is-IS",
"it-CH",
"it-IT",
"iu-Cans-CA",
"iu-Latn-CA",
"ja-JP",
"ka-GE",
"kk-KZ",
"kl-GL",
"km-KH",
"kn-IN",
"kok-IN",
"ko-KR",
"ky-KG",
"lb-LU",
"lo-LA",
"lt-LT",
"lv-LV",
"mi-NZ",
"mk-MK",
"ml-IN",
"mn-MN",
"mn-Mong-CN",
"moh-CA",
"mr-IN",
"ms-BN",
"ms-MY",
"mt-MT",
"nb-NO",
"ne-NP",
"nl-BE",
"nl-NL",
"nn-NO",
"nso-ZA",
"oc-FR",
"or-IN",
"pa-IN",
"pl-PL",
"prs-AF",
"ps-AF",
"pt-BR",
"pt-PT",
"qut-GT",
"quz-BO",
"quz-EC",
"quz-PE",
"rm-CH",
"ro-RO",
"ru-RU",
"rw-RW",
"sah-RU",
"sa-IN",
"se-FI",
"se-NO",
"se-SE",
"si-LK",
"sk-SK",
"sl-SI",
"sma-NO",
"sma-SE",
"smj-NO",
"smj-SE",
"smn-FI",
"sms-FI",
"sq-AL",
"sr-Cyrl-BA",
"sr-Cyrl-CS",
"sr-Cyrl-ME",
"sr-Cyrl-RS",
"sr-Latn-BA",
"sr-Latn-CS",
"sr-Latn-ME",
"sr-Latn-RS",
"sv-FI",
"sv-SE",
"sw-KE",
"syr-SY",
"ta-IN",
"te-IN",
"tg-Cyrl-TJ",
"th-TH",
"tk-TM",
"tn-ZA",
"tr-TR",
"tt-RU",
"tzm-Latn-DZ",
"ug-CN",
"uk-UA",
"ur-PK",
"uz-Cyrl-UZ",
"uz-Latn-UZ",
"vi-VN",
"wo-SN",
"xh-ZA",
"yo-NG",
"zh-CN",
"zh-HK",
"zh-MO",
"zh-SG",
"zh-TW",
"zu-ZA"
];
localesList.forEach(lcl => {
if ("2014-05-11" === new Date('Sun May 11,2014').toLocaleDateString(lcl)) {
console.log(lcl, new Date('Sun May 11,2014').toLocaleDateString(lcl));
}
});
The 2021 solution using Intl.
The new Intl Object is now supported on all browsers.
You can choose the format by choosing a "locale" that uses the required format.
The Swedish locale uses the format "yyyy-mm-dd":
// Create a date
const date = new Date(2021, 10, 28);
// Create a formatter using the "sv-SE" locale
const dateFormatter = Intl.DateTimeFormat('sv-SE');
// Use the formatter to format the date
console.log(dateFormatter.format(date)); // "2021-11-28"
Downsides of using Intl:
You cannot "unformat" or "parse" strings using this method
You have to search for the required format (for instance on Wikipedia) and cannot use a format-string like "yyyy-mm-dd"
Simply use this:
var date = new Date('1970-01-01'); // Or your date here
console.log((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());
Simple and sweet ;)
Shortest
.toJSON().slice(0,10);
var d = new Date('Sun May 11,2014' +' UTC'); // Parse as UTC
let str = d.toJSON().slice(0,10); // Show as UTC
console.log(str);
toISOString() assumes your date is local time and converts it to UTC. You will get an incorrect date string.
The following method should return what you need.
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
Source: https://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
In the most of cases (no time zone handling) this is enough:
date.toISOString().substring(0,10)
Example
var date = new Date();
console.log(date.toISOString()); // 2022-07-04T07:14:08.925Z
console.log(date.toISOString().substring(0,10)); // 2022-07-04
Retrieve year, month, and day, and then put them together. Straight, simple, and accurate.
function formatDate(date) {
var year = date.getFullYear().toString();
var month = (date.getMonth() + 101).toString().substring(1);
var day = (date.getDate() + 100).toString().substring(1);
return year + "-" + month + "-" + day;
}
//Usage example:
alert(formatDate(new Date()));
new Date('Tue Nov 01 2022 22:14:53 GMT-0300').toLocaleDateString('en-CA');
new Date().toLocaleDateString('pt-br').split( '/' ).reverse( ).join( '-' );
or
new Date().toISOString().split('T')[0]
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString()
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString().split('T')[0]
Try this!
When ES2018 rolls around (works in chrome) you can simply regex it
(new Date())
.toISOString()
.replace(
/^(?<year>\d+)-(?<month>\d+)-(?<day>\d+)T.*$/,
'$<year>-$<month>-$<day>'
)
2020-07-14
Or if you'd like something pretty versatile with no libraries whatsoever
(new Date())
.toISOString()
.match(
/^(?<yyyy>\d\d(?<yy>\d\d))-(?<mm>0?(?<m>\d+))-(?<dd>0?(?<d>\d+))T(?<HH>0?(?<H>\d+)):(?<MM>0?(?<M>\d+)):(?<SSS>(?<SS>0?(?<S>\d+))\.\d+)(?<timezone>[A-Z][\dA-Z.-:]*)$/
)
.groups
Which results in extracting the following
{
H: "8"
HH: "08"
M: "45"
MM: "45"
S: "42"
SS: "42"
SSS: "42.855"
d: "14"
dd: "14"
m: "7"
mm: "07"
timezone: "Z"
yy: "20"
yyyy: "2020"
}
Which you can use like so with replace(..., '$<d>/$<m>/\'$<yy> # $<H>:$<MM>') as at the top instead of .match(...).groups to get
14/7/'20 # 8:45
const formatDate = d => [
d.getFullYear(),
(d.getMonth() + 1).toString().padStart(2, '0'),
d.getDate().toString().padStart(2, '0')
].join('-');
You can make use of padstart.
padStart(n, '0') ensures that a minimum of n characters are in a string and prepends it with '0's until that length is reached.
join('-') concatenates an array, adding '-' symbol between every elements.
getMonth() starts at 0 hence the +1.
To consider the timezone also, this one-liner should be good without any library:
new Date().toLocaleString("en-IN", {timeZone: "Asia/Kolkata"}).split(',')[0]
You can try this: https://www.npmjs.com/package/timesolver
npm i timesolver
Use it in your code:
const timeSolver = require('timeSolver');
const date = new Date();
const dateString = timeSolver.getString(date, "YYYY-MM-DD");
You can get the date string by using this method:
getString
I suggest using something like formatDate-js instead of trying to replicate it every time. Just use a library that supports all the major strftime actions.
new Date().format("%Y-%m-%d")
Unfortunately, JavaScript's Date object has many pitfalls. Any solution based on Date's builtin toISOString has to mess with the timezone, as discussed in some other answers to this question. The clean solution to represent an ISO-8601 date (without time) is given by Temporal.PlainDate from the Temporal proposal. As of February 2021, you have to choose the workaround that works best for you.
use Date with vanilla string concatenation
Assuming that your internal representation is based on Date, you can perform manual string concatenation. The following code avoids some of Date's pitfalls (timezone, zero-based month, missing 2-digit formatting), but there might be other issues.
function vanillaToDateOnlyIso8601() {
// month May has zero-based index 4
const date = new Date(2014, 4, 11);
const yyyy = date.getFullYear();
const mm = String(date.getMonth() + 1).padStart(2, "0"); // month is zero-based
const dd = String(date.getDate()).padStart(2, "0");
if (yyyy < 1583) {
// TODO: decide how to support dates before 1583
throw new Error(`dates before year 1583 are not supported`);
}
const formatted = `${yyyy}-${mm}-${dd}`;
console.log("vanilla", formatted);
}
use Date with helper library (e.g. formatISO from date-fns)
This is a popular approach, but you are still forced to handle a calendar date as a Date, which represents
a single moment in time in a platform-independent format
The following code should get the job done, though:
import { formatISO } from "date-fns";
function dateFnsToDateOnlyIso8601() {
// month May has zero-based index 4
const date = new Date(2014, 4, 11);
const formatted = formatISO(date, { representation: "date" });
console.log("date-fns", formatted);
}
find a library that properly represents dates and times
I wish there was a clean and battle-tested library that brings its own well-designed date–time representations. A promising candidate for the task in this question was LocalDate from #js-joda/core, but the library is less active than, say, date-fns. When playing around with some example code, I also had some issues after adding the optional #js-joda/timezone.
However, the core functionality works and looks very clean to me:
import { LocalDate, Month } from "#js-joda/core";
function jodaDateOnlyIso8601() {
const someDay = LocalDate.of(2014, Month.MAY, 11);
const formatted = someDay.toString();
console.log("joda", formatted);
}
experiment with the Temporal-proposal polyfill
This is not recommended for production, but you can import the future if you wish:
import { Temporal } from "proposal-temporal";
function temporalDateOnlyIso8601() {
// yep, month is one-based here (as of Feb 2021)
const plainDate = new Temporal.PlainDate(2014, 5, 11);
const formatted = plainDate.toString();
console.log("proposal-temporal", formatted);
}
Here is one way to do it:
var date = Date.parse('Sun May 11,2014');
function format(date) {
date = new Date(date);
var day = ('0' + date.getDate()).slice(-2);
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var year = date.getFullYear();
return year + '-' + month + '-' + day;
}
console.log(format(date));
Date.js is great for this.
require("datejs")
(new Date()).toString("yyyy-MM-dd")
Simply Retrieve year, month, and day, and then put them together.
function dateFormat(date) {
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
return `${year}-${month}-${day}`;
}
console.log(dateFormat(new Date()));
None of these answers quite satisfied me. I wanted a cross-platform solution that gave me the day in the local timezone without using any external libraries.
This is what I came up with:
function localDay(time) {
var minutesOffset = time.getTimezoneOffset()
var millisecondsOffset = minutesOffset*60*1000
var local = new Date(time - millisecondsOffset)
return local.toISOString().substr(0, 10)
}
That should return the day of the date, in YYYY-MM-DD format, in the timezone the date references.
So for example, localDay(new Date("2017-08-24T03:29:22.099Z")) will return "2017-08-23" even though it's already the 24th at UTC.
You'll need to polyfill Date.prototype.toISOString for it to work in Internet Explorer 8, but it should be supported everywhere else.
A few of the previous answer were OK, but they weren't very flexible. I wanted something that could really handle more edge cases, so I took #orangleliu 's answer and expanded on it. https://jsfiddle.net/8904cmLd/1/
function DateToString(inDate, formatString) {
// Written by m1m1k 2018-04-05
// Validate that we're working with a date
if(!isValidDate(inDate))
{
inDate = new Date(inDate);
}
// See the jsFiddle for extra code to be able to use DateToString('Sun May 11,2014', 'USA');
//formatString = CountryCodeToDateFormat(formatString);
var dateObject = {
M: inDate.getMonth() + 1,
d: inDate.getDate(),
D: inDate.getDate(),
h: inDate.getHours(),
m: inDate.getMinutes(),
s: inDate.getSeconds(),
y: inDate.getFullYear(),
Y: inDate.getFullYear()
};
// Build Regex Dynamically based on the list above.
// It should end up with something like this: "/([Yy]+|M+|[Dd]+|h+|m+|s+)/g"
var dateMatchRegex = joinObj(dateObject, "+|") + "+";
var regEx = new RegExp(dateMatchRegex,"g");
formatString = formatString.replace(regEx, function(formatToken) {
var datePartValue = dateObject[formatToken.slice(-1)];
var tokenLength = formatToken.length;
// A conflict exists between specifying 'd' for no zero pad -> expand
// to '10' and specifying yy for just two year digits '01' instead
// of '2001'. One expands, the other contracts.
//
// So Constrict Years but Expand All Else
if (formatToken.indexOf('y') < 0 && formatToken.indexOf('Y') < 0)
{
// Expand single digit format token 'd' to
// multi digit value '10' when needed
var tokenLength = Math.max(formatToken.length, datePartValue.toString().length);
}
var zeroPad = (datePartValue.toString().length < formatToken.length ? "0".repeat(tokenLength) : "");
return (zeroPad + datePartValue).slice(-tokenLength);
});
return formatString;
}
Example usage:
DateToString('Sun May 11,2014', 'MM/DD/yy');
DateToString('Sun May 11,2014', 'yyyy.MM.dd');
DateToString(new Date('Sun Dec 11,2014'),'yy-M-d');
If you use momentjs, now they include a constant for that format YYYY-MM-DD:
date.format(moment.HTML5_FMT.DATE)
You can use this function for better format and easy of use:
function convert(date) {
const d = Date.parse(date)
const date_obj = new Date(d)
return `${date_obj.getFullYear()}-${date_obj.toLocaleString("default", { month: "2-digit" })}-${date_obj.toLocaleString("default", { day: "2-digit"})}`
}
This function will format the month as 2-digit output as well as the days
Yet another combination of the answers. Nicely readable, but a little lengthy.
function getCurrentDayTimestamp() {
const d = new Date();
return new Date(
Date.UTC(
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
d.getMinutes(),
d.getSeconds()
)
// `toIsoString` returns something like "2017-08-22T08:32:32.847Z"
// and we want the first part ("2017-08-22")
).toISOString().slice(0, 10);
}

Convert dd-mm-yy to javascript date object

I get a date which comes in this format: ddmmyy, and I need to do some validation with it.
How can I parse it to a javascript date object?
I've tried to search, and there are a lot on the ddmmyyyy format, but not the format I get.
EDIT: Example date: 031290 = 3.12.1990.
You could parse ddmmyyyy into a yyyy-mm-dd form and pass that to Date.parse.
Date.parse( "02032002".replace(/^(\d\d)(\d\d)(\d{4})$/, "$3-$2-$1") );
Or otherwise split it up and use the Date's setters / constructor:
// month - 1 : in this form January is 0, December is 11
var date = new Date( year, month - 1, date );
Just noticed the YY vs YYYY part of the question:
var parts = /^(\d\d)(\d\d)(\d{2})$/.exec( "190304" );
var date = new Date( parts[3], parts[2]-1, parts[1] );
You could augment that with some code which adds a 20 or 19 depending if the year is over or below a certain threshold (like 70 : < 70 indicates 20xx and >= 70 indictaes 19xx years).
Try this:
var a="221178".split(/(?=(?:..)*$)/);
var result=new Date ( parseInt(a[2],10) + 1900 , a[1]-1 , a[0] )
result:
Tue Nov 22 1978 00:00:00 GMT+0200
JSBIN
If you want a non-regex solution, you can use new Date(year, month, date) constructor, and simple cut strings into those parts. It's not fancy, but it clear in what it does:
function parse2date(str){
var year = parseInt(str.substr(4, 2));
var month = parseInt(str.substr(2, 2));
var day = parseInt(str.substr(0, 2))
return new Date(year < 20 ? 2000 + year : year, month - 1, day)
}
this function assumes if 2-disgit years is below 20 - then it is meant to be in 2000s, otherwise it's in 1900s. But you can adjust the limit. Try calling it:
alert(parse2date('031290'));
Ok, so here is how I solved it.
The answers here is right, except I wasn't happy with the way the detection of the current century worked; so I basically did this:
var date = new Date(year + 2000, month - 1, day);
if (date > new Date())
date.setYear(year + 1900);
With this code, I can maximum validate an age of 100, but that shouldn't be a problem.
Mukul Goel in the comment below points out it can only validate dates in the future. Probably right, I haven't checked it myself.

Why doesn't this new Date work in javascript?

I'm trying to display a date with format "MMM. dd HH:mm:ss.nnn". It is rendering it incorrectly in IE and I have spent quite some time and I can't figure out why I can't get this to work.
I know that Date.UTC returns the number of miliseconds in a Date object since Jan 1, 1970. So,
var newDate = new Date(Date.UTC(year, month[, date[, hrs[, min[, sec[, ms]]]]])
newDate.toString("MMM. dd HH:mm:ss.")+row.timestamp.getMilliseconds();
will work.
Example:
var newDate = new Date(Date.UTC(1950, 10, 10, 10, 09, 09, 100));
row.timestamp_f = newDate.toString("MMM. dd HH:mm:ss."); // Output => Nov. 10 05:09:09.
But, I am interating this from a jquey.each function so the date string that I am working with is an ISO 8601: "2013-03-12T15:14:10.483". So, this is what I have in mind.
var numMilisecond = Date.parse(row.timestamp);
var newDate = new Date(numMilisecond);
row.timestamp_f = newDate.toString("MMM. dd HH:mm:ss."); // Output => Dec. 31 19:00:00.
row.timestamp is from a JSON response
{"timestamp":"2013-03-12T15:14:10.483" ...}
Why doesn't the code work? Date.parse should return the number of miliseconds since Jan 1, 1970 and then I create a new Date obj and then convert it to string just like the code in the first snipet. What am I doing wrong?
Thanks.
Date.toString shouldn't accept any arguments. If you want a true date-formatting solution, you'll need to use a plugin or roll your own.
var shortmonths = ['Jan','Feb','Mar','Apr',]; // remaining months are left as an exercise for the reader
row.timestamp_f = shortmonths[newDate.getMonth()]
+ ". "+newDate.getDate() + " "
+ newDate.toLocaleTimeString() + ".";

How to the get the beginning of day of a date in javascript -- factoring in timezone

I am struggling to find out the beginning of day factoring in timezones in javascript. Consider the following:
var raw_time = new Date(this.created_at);
var offset_time = new Date(raw_hour.getTime() + time_zone_offset_in_ms);
// This resets timezone to server timezone
var offset_day = new Date(offset_time.setHours(0,0,0,0))
// always returns 2011-12-08 05:00:00 UTC, no matter what the offset was!
// This has the same issue:
var another_approach_offset_day = new Date(offset_time.getFullYear(),offset_time.getMonth(),offset_time.getHours())
I expect when i pass a Pacific Timezone offset, to get: 2011-12-08 08:00:00 UTC and so on.
What is the correct way to achieve this?
I think that part of the issue is that setHours method sets the hour (from 0 to 23), according to local time.
Also note that I am using javascript embedded in mongo, so I am unable to use any additional libraries.
Thanks!
Jeez, so this was really hard for me, but here is the final solution that I came up with the following solution. The trick was I need to use setHours or SetUTCHours to get the beginning of a day -- the only choices I have are system time and UTC. So I get the beginning of a UTC day, then add back the offset!
// Goal is given a time and a timezone, find the beginning of day
function(timestamp,selected_timezone_offset) {
var raw_time = new Date(timestamp)
var offset_time = new Date(raw_time.getTime() + selected_timezone_offset);
offset_time.setUTCHours(0,0,0,0);
var beginning_of_day = new Date(offset_time.getTime() - selected_timezone_offset);
return beginning_of_day;
}
In JavaScript all dates are stored as UTC. That is, the serial number returned by date.valueOf() is the number of milliseconds since 1970-01-01 00:00:00 UTC. But, when you examine a date via .toString() or .getHours(), etc., you get the value in local time. That is, the local time of the system running the script. You can get the value in UTC with methods like .toUTCString() or .getUTCHours(), etc.
So, you can't get a date in an arbitrary timezone, it's all UTC (or local). But, of course, you can get a string representation of a date in whatever timezone you like if you know the UTC offset. The easiest way would be to subtract the UTC offset from the date and call .getUTCHours() or .toUTCString() or whatever you need:
var d = new Date();
d.setMinutes(d.getMinutes() - 480); // get pacific standard time
d.toUTCString(); // returns "Fri, 9 Dec 2011 12:56:53 UTC"
Of course, you'll need to ignore that "UTC" at the end if you use .toUTCString(). You could just go:
d.toUTCString().replace(/UTC$/, "PST");
Edit: Don't worry about when timezones overlap date boundaries. If you pass setHours() a negative number, it will subtract those hours from midnight yesterday. Eg:
var d = new Date(2011, 11, 10, 15); // d represents Dec 10, 2011 at 3pm local time
d.setHours(-1); // d represents Dec 9, 2011 at 11pm local time
d.setHours(-24); // d represents Dec 8, 2011 at 12am local time
d.setHours(52); // d represents Dec 10, 2011 at 4am local time
Where does the time_zone_offset_in_ms variable you use come from? Perhaps it is unreliable, and you should be using Date's getTimezoneOffset() method. There is an example at the following URL:
http://www.w3schools.com/jsref/jsref_getTimezoneOffset.asp
If you know the date from a different date string you can do the following:
var currentDate = new Date(this.$picker.data('date'));
var today = new Date();
today.setHours(0, -currentDate.getTimezoneOffset(), 0, 0);
(based on the codebase for a project I did)
var aDate = new Date();
var startOfTheDay = new Date(aDate.getTime() - aDate.getTime() % 86400000)
Will create the beginning of the day, of the day in question
You can make use of Intl.DateTimeFormat. This is also how luxon handles timezones.
The code below can convert any date with any timezone to its beginging/end of the time.
const beginingOfDay = (options = {}) => {
const { date = new Date(), timeZone } = options;
const parts = Intl.DateTimeFormat("en-US", {
timeZone,
hourCycle: "h23",
hour: "numeric",
minute: "numeric",
second: "numeric",
}).formatToParts(date);
const hour = parseInt(parts.find((i) => i.type === "hour").value);
const minute = parseInt(parts.find((i) => i.type === "minute").value);
const second = parseInt(parts.find((i) => i.type === "second").value);
return new Date(
1000 *
Math.floor(
(date - hour * 3600000 - minute * 60000 - second * 1000) / 1000
)
);
};
const endOfDay = (...args) =>
new Date(beginingOfDay(...args).getTime() + 86399999);
const beginingOfYear = () => {};
console.log(beginingOfDay({ timeZone: "GMT" }));
console.log(endOfDay({ timeZone: "GMT" }));
console.log(beginingOfDay({ timeZone: "Asia/Tokyo" }));
console.log(endOfDay({ timeZone: "Asia/Tokyo" }));

Format Date in Javascript

How to format this:
/Date(1292962456255)/
as regular looking date in JavaScript/jQuery?
This is what I call an "Microsoft Date" and the following function will convert the encoded date to a javascript date time
var msDateToJSDate = function(msDate) {
var dtE = /^\/Date\((-?[0-9]+)\)\/$/.exec(msDate);
if (dtE) {
var dt = new Date(parseInt(dtE[1], 10));
return dt;
}
return null;
}
Check out moment.js! It's "A lightweight javascript date library for parsing, manipulating, and formatting dates". It is a really powerful little library.
Here's an example...
var today = moment(new Date());
today.format("MMMM D, YYYY h:m A"); // outputs "April 11, 2012 2:32 PM"
// in one line...
moment().format("MMMM D, YYYY h:m A"); // outputs "April 11, 2012 2:32 PM"
Here's another example...
var a = moment([2012, 2, 12, 15, 25, 50, 125]);
a.format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Monday, March 12th 2012, 3:25:50 pm"
a.format("ddd, hA"); // "Mon, 3PM"
a.format("D/M/YYYY"); // "12/3/2012"
Also, its worth mentioning to checkout date.js. I think the two libraries complement each other.
The number is a timestamp with millisecond resolution. This number can be passed to JavaScript's Date class' constructor. All that is needed is some code to extract it from the string:
var dateString = "/Date(1292962456255)/";
var matches = dateString.match(/^\/Date\((\d+)\)\/$/);
var date = new Date(parseInt(matches[1], 10));
The regexp on the second line gets a bit messy since the string contains /, ( and ) at precisely the positions that they are needed in the regexp (are you sure what you have is strings that look like that, and not a description of a pattern that would extract them?).
Another way of doing it is to use eval:
var dateString = "/Date(1292962456255)/";
var date = eval("new " + dateString.substring(1, dateString.length - 1));
but that may open up for an XSS attack, so I don't recommend it.
I think this a microtime. Similar to PHP's microtime function. Or in new Date().getTime() in JavaScript.
// PHP
$ php -r "var_dump(microtime(true));"
float(1292963152.1249)
// JavaScript
new Date().getTime()
1292963411830

Categories