Skip to content

Instantly share code, notes, and snippets.

@v-stickykeys
Created November 23, 2018 21:11
Show Gist options
  • Save v-stickykeys/1941593a94883fa8c4b90926020cb59a to your computer and use it in GitHub Desktop.
Save v-stickykeys/1941593a94883fa8c4b90926020cb59a to your computer and use it in GitHub Desktop.
Lightest way to get the date and time in the format you want
const getTodayDefault = () => {
return new Date().toDateString();
}
const getTodayCondensed = () => {
return new Date().toLocaleDateString();
}
const getTodayExpanded = () => {
let d = new Date();
let options = {
weekday: 'long',
month: 'long',
day: 'numeric',
year: 'numeric',
};
return d.toLocaleDateString(undefined, options);
}
const getTimeNow = () => {
let d = new Date();
let options = {
hour12: true,
hour: '2-digit',
minute: '2-digit',
timeZoneName: "short"
};
return d.toLocaleTimeString(undefined, options);
}
const getRawTimestampNow = () => {
return Date.now();
}
const getRawDateTimeNow = () => {
return new Date().toString();
}
/* Your custom format here: */
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
module.exports = {
getTodayDefault,
getTodayCondensed,
getTodayExpanded,
getTimeNow,
getRawTimestampNow,
getRawDateTimeNow
}

Here is an example of how to use this in React JS:

import dateTime from '../utils/dateTime';

// ...

return(
  <div>
    <p>Default: {dateTime.getTodayDefault()}</p>
    <p>Condensed: {dateTime.getTodayCondensed()}</p>
    <p>Expanded: {dateTime.getTodayExpanded()}</p>
    <p>Time Now: {dateTime.getTimeNow()}</p>
    <p>Raw Timestamp Now: {dateTime.getRawTimestampNow()}</p>
    <p>Raw Date Time Now: {dateTime.getRawDateTimeNow()}</p>
  </div>
)

Feel free to modify this for your own needs. The function names were selected such that they would not conflict with existing Date object function names.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment