Javascript DateFormat for different timezones - javascript

I'm a Java developer and I'm used to the SimpleDateFormat class that allows me to format any date to any format by settings a timezone.
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
System.out.println(sdf.format(date)); // Prints date in Los Angeles
sdf.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
System.out.println(sdf.format(date)); // Prints same date in Chicago
SimpleDateFormat is a pretty neat solution in Java but unfortunately I can't find any similar alternative in Javascript.
I'm extending the Date prototype in Javascript to do exactly the same. I have dates in Unix format but I want to format them in different timezones.
Date.prototype.format = function(format, timezone) {
// Now what?
return formattedDate;
}
I'm looking for a neat way to do this rather than a hack.
Thanks

There is a way to format for time zones.
console.log(new Date().toLocaleDateString('en-US', {timeZone: 'America/Denver'}))
// 11/13/2018
console.log(new Date().toLocaleTimeString('en-US', {timeZone: 'America/Denver'}))
// 2:30:54 PM
console.log(new Date().toLocaleTimeString('en-US', {timeZone: 'America/New_York'}))
// 4:31:26 PM
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString

The ISO Extended format for common date is YYYY-MM-DD, and for time is hh:mm:ss. Either format can be understood, unambiguously, worldwide.
See also:
http://jibbering.com/faq/#dates

If you're just passing the raw TZ there's nothing really complicated about adjusting the hours.
My example below is of course abbreviated. Yours may get quite long depending on how many patterns you'd handle.
Date.prototype.format = function(format, tzAdjust) {
// adjust timezone
this.setHours(this.getHours()+tzAdjust)
// pad zero helper - return "09" or "12"
var two = function(s){ return s+"".length==1 ? "0"+s : s+""; }
// replace patterns with date numbers
return format.replace(/dd|MM|yyyy|hh|mm|ss/g, function(pattern){
switch(pattern){
case "d" : return this.getDate();
case "dd" : return two(this.getDate());
}
});
}

Attempting to (ever so slightly) improve upon mwilcox's suggestion:
Date.prototype.format = function(format, tzAdjust) {
// get/setup a per-date-instance tzDate object store
var tzCache = this.__tzCache = this.__tzCache || (this.__tzCache = {});
// fetch pre-defined date from cache
var tzDate = tzCache[tzAdjust];
if ( !tzDate )
{
// on miss - then create a new tzDate and cache it
tzDate = tzCache[tzAdjust] = new Date( this );
// adjust by tzAdjust (assuming it's in minutes
// to handle those weird half-hour TZs :)
tzDate.setUTCMinutes( tzDate.getUTCMinutes()+tzAdjust );
}
return format.replace(/dd|MM|yyyy|hh|mm|ss/g, function(pattern){
// replace each format tokens with a value
// based on tzDate's corresponding UTC property
});
}

You are clearly asking two questions in one, formatting and time zone. They need to be addressed separately. Formatting is pretty trivial, if none of the other answers will do for that you will have to be more specific.
As for the time and time zone, if you have your server inject the UTC time, preferably as UNIX time in milliseconds, into the JavaScript, you can compare that to the time on the client machine, and thus work out how far from UTC the client is. Then you can calculate the time of any time zone you want.
Edit: I actually didn't know JavaScript also had built in UTC time until I checked on the internet, neat.
In any case, I suppose this is want you want:
Date.prototype.format=function(format,timezone){
var obj=new Date(this.getTime()+this.getTimezoneOffset()*60000+timezone*3600000);
var two=function(s){
return s<10?"0"+s:s+"";
}
return format.replace(/dd|MM|yyyy|hh|mm|ss/g, function(pattern){
switch(pattern){
case "dd" : return two(obj.getDate());
case "MM" : return two(obj.getMonth()+1);
case "yyyy" : return obj.getFullYear();
case "hh" : return two(obj.getHours());
case "mm" : return two(obj.getMinutes());
case "ss" : return two(obj.getSeconds());
}
});
}
You can add in more patterns if you need.

Don't write your own stuff; just get datejs: http://www.datejs.com/
You can figure out what the timezone offset is set to in the execution environment like this:
var local = new Date();
var utc = Date.UTC(local.getFullYear(), local.getMonth(), local.getDate(), local.getHours(), local.getMinutes(), local.getSeconds(), local.getMilliseconds());
var tz = (utc - local.getTime()) / (60 * 60 * 1000);

This is an old question, but since I found it:
As mentioned, there's nothing reasonable built-in.
As for libs, there is Moment Timezone for Moment.js.
Here is a JSfiddle with an example: http://jsfiddle.net/kunycrkb/
The same code inline:
var m = moment("2014-06-01T13:05:00Z");
var f = "HH:mm z";
$("#results").text(m.tz("UTC").format(f) + " is " + m.tz("EST").format(f) + "!");

Since my requirement was a typescript solution but I stumbled here I used this answer to write my typescript function.
Based on answer above, a function in typescript which converts a timestamp or a date object into a formatted local time string.
const formatDateString = (date_or_ts:Date|number):string=>{
let obj:Date;
if(typeof date_or_ts === "number"){
obj = new Date(date_or_ts*1000);
// obj=new Date(obj.getTime()+obj.getTimezoneOffset()*60000+timezone*3600000);
}else{
obj = date_or_ts;
}
const format = "dd-MM-yyyy hh:mm:ss";
let two=function(s:number){
return s<10?"0"+s:s+"";
}
return format.replace(/dd|MM|yyyy|hh|mm|ss/g, function(pattern){
const months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
switch(pattern){
case "dd" : return two(obj.getDate()).toString();
case "MM" : return months[obj.getMonth()];
case "yyyy" : return obj.getFullYear().toString();
case "hh" : return two(obj.getHours()).toString();
case "mm" : return two(obj.getMinutes()).toString();
case "ss" : return two(obj.getSeconds()).toString();
default: return "";
}
});
}

Related

How to convert a date to ISO format but with timezone info in place of the 'Z' in Javascript?

I have always worked with dates in ISO format that ends with a 'Z'. But now I have to replace that 'Z' with timezone info like +08:00.
In other words, currently I have this format 2020-01-17T00:30:00.000Z, but now I need it in this format 2020-01-17T08:30:00+08:00.
Looks like popular date library like moment and dayjs convert date to ISO format without 'Z' too by default. Is that still considered an 'ISO' date format? And I can't find out how to do it with vanilla Javascript and doing the .toISOString() always gives me the 'Z'..
If you get the date string in the ISO format, but you want to get the string in a certain timezone, with the timezone.
Then here's a simple function that does just that.
function getISODateStampWithTZ (date, tzHours)
{
let dateTz = new Date(date);
dateTz.setUTCHours(tzHours);
return dateTz.toISOString().replace(/Z$/,
(tzHours<0 ? '-' : '+') +
(Math.abs(tzHours)<10 ? '0'+Math.abs(tzHours) : Math.abs(tzHours)) +
':00');
}
const date = new Date('2020-01-17T00:30:00.000Z');
console.log(date.toISOString());
console.log(getISODateStampWithTZ(date, 8));
console.log(getISODateStampWithTZ(date, -1));
Such function could also be added to the Date prototype.
The example below prefixes the function with 'custom' to make it distinct from standard methods.
Date.prototype.customToISOStringTZ = function (tzHours)
{
let dateTz = new Date(this);
dateTz.setUTCHours(tzHours);
return dateTz.toISOString().replace(/Z$/,
(tzHours<0 ? '-' : '+') +
(Math.abs(tzHours)<10 ? '0'+Math.abs(tzHours) : Math.abs(tzHours)) +
':00');
}
const date = new Date('2020-01-17T00:30:00.000Z');
console.log(date.toISOString());
console.log(date.customToISOStringTZ(8));
console.log(date.customToISOStringTZ(-1));
parser.isoparse('2019-08-28T14:34:25.518993Z')
use this to get correct format
The Z ("Zulu") on the end means UTC, ie. an offset from UTC of zero. I'm assuming you want to convert from UTC to local time, in which case you need to calculate the offset from UTC:
function convertUTCDateToLocalDate(date) {
const newDate = new Date(date.getTime() + date.getTimezoneOffset() * 60 * 1000);
const offset = date.getTimezoneOffset() / 60;
const hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
Usage:
const date = new Date("2020-01-17T00:30:00.000Z")
const newDate = convertUTCDateToLocalDate(date)
newDate.toISOString() // "2020-01-17T01:30:00.000+01:00"
Beware! This solution won't work for timezones where the offset isn't a full hour.
If you're running this in a browser I'd strongly recommend using a tool like moment.

How to get the Australian Time Zone using Javascript? (Not JQuery)

I am trying to help a friend to get the Australian Time Zone for the University Assignment and finding difficulty.
Could someone point us in the right direction?
Thank you!
<script>
function Timezone() {
var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
document.getElementById("add").innerHTML = currentTimeZoneOffsetInHours;
}
</script>
<p id="add"></p>
You simply use
let AuDate = new Date().toLocaleString("en-US", {timeZone: "Australia/Sydney"});
By looking at your code, looks like you are trying to get the current date and time of an Australian timezone. Lets say you want Australian Eastern Standard Time (AEST) and you want the date displayed how they would in Australia DD-MM-YYYY then do the following:
var timestamp_UTC = new Date();
var readable_timestamp_AEST = timestamp_UTC.toLocaleDateString("en-AU", {timeZone: "Australia/Sydney"}).replace(/\//g, "-") + ' ' + somestamp.toLocaleTimeString("en-AU", {timeZone: "Australia/Sydney"});
"en-AU" is the locales argument which tells the toLocalDateString to display the date as DD-MM-YYYY and the second argument is for options (timeZone is just one such possible option). Info about toLocalDateString function can be found here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
Here is some information about the Date() function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Hope this clears up a few things around getting times and dates from the Date() function.
I think i understand what you mean. But before that i'd like to make 2 points:
1: The Timezone() function should be called somewhere.
<script>
function Timezone() {
var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
document.getElementById("add").innerHTML = currentTimeZoneOffsetInHours;
}
Timezone();
</script>
2: The convention usually is that methods start with a lower case letter. Maybe updateTimezone() would be more appropriate.
Your question can be interpreted in 2 ways now:
you want your timezone's offset in hours and for this the code above should work. getTimezoneOffset() is the way to go.
you want a human readable name of your timezone, as you can see on my site currentmillis.com (in my case it says GTB Summer). You can look in my source code to see how i achieve this:
var s = date.toString();
var iOfP = s.indexOf('('); // index of parenthesis
if (iOfP < 0) {
s = s.substring(s.lastIndexOf(' ') + 1);
} else {
s = s.substring(iOfP+1, s.length-1);
}
if (s.length > 4 && s.lastIndexOf(" Time") == s.length-5){
s = s.substring(0, s.length-5);
}
timezoneM.innerHTML = s;
This works because when you call toString() on the date the result should contain the full name of your timezone: w3schools.com/jsref/jsref_tostring_date.asp

Javascript - Convert ####-##-## to Epoch time

Is there a way to take a date object from a HTML object in the format of ####-##-## and convert it to epoch time. For example, the user inputs the value of August 12, 2012 which shows as 2012-08-12 when I print out the .val() of it, and I need to get this in Epoch time.
EDIT
Code to date:
if (hvStartDate == "") {
hvStartDate = "start"
}
else {
console.log($("#hv-start-date").val()); // => 2012-08-20
hvStartDate = new Date($("#hv-start-date").val()).getTime(); // => NaN
}
if (hvEndDate == "") {
hvEndDate = "end"
}
else {
hvEndDate = new Date($("#hv-end-date").val()).getTime(); // => NaN
}
var myTmp = new Date("2012-08-20");
console.log(myTmp.getTime()); // => NaN
Javascript's Date built-in allows you to pass a date string into its constructor, giving you a Date based on that string. From there, calling getTime( ) will give you the epoch time.
new Date($('.user-value').val()).getTime(); // => epoch time
new Date('2012-08-12').getTime(); // 1344729600000
Caveat: Beware of locale strings and locale-specific date formatting (for example, the position of days and months switch depending on locale).
EDIT: Based on your code in the comment below, here's what you need to do. Notice that you have to instantiate a new Date Object before calling getTime():
if (hvStartDate == "") {
hvStartDate = "start"
}
else {
hvStartDate = new Date($("#hv-start-date").val()).getTime();
}
Simply use the getTime() function. It returns the number of milliseconds since Epoch :
var msSinceEpoch = myDate.getTime();
Complete Date reference at MDN : https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
EDIT : if you have to parse it too, you may :
use new Date(theString) if it has the good format
set yourself the different date fields (see reference) after having parsed it
use a date parsing library. I use this one : http://www.datejs.com/ which is very powerful for all date parsing, computing and formating.

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

Using NodeJS, I want to format a Date into the following string format:
var ts_hms = new Date(UTC);
ts_hms.format("%Y-%m-%d %H:%M:%S");
How do I do that?
If you're using Node.js, you're sure to have EcmaScript 5, and so Date has a toISOString method. You're asking for a slight modification of ISO8601:
new Date().toISOString()
> '2012-11-04T14:51:06.157Z'
So just cut a few things out, and you're set:
new Date().toISOString().
replace(/T/, ' '). // replace T with a space
replace(/\..+/, '') // delete the dot and everything after
> '2012-11-04 14:55:45'
Or, in one line: new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')
ISO8601 is necessarily UTC (also indicated by the trailing Z on the first result), so you get UTC by default (always a good thing).
UPDATE 2021-10-06: Added Day.js and remove spurious edit by #ashleedawg
UPDATE 2021-04-07: Luxon added by #Tampa.
UPDATE 2021-02-28: It should now be noted that Moment.js is no longer being actively developed. It won't disappear in a hurry because it is embedded in so many other things. The website has some recommendations for alternatives and an explanation of why.
UPDATE 2017-03-29: Added date-fns, some notes on Moment and Datejs
UPDATE 2016-09-14: Added SugarJS which seems to have some excellent date/time functions.
OK, since no one has actually provided an actual answer, here is mine.
A library is certainly the best bet for handling dates and times in a standard way. There are lots of edge cases in date/time calculations so it is useful to be able to hand-off the development to a library.
Here is a list of the main Node compatible time formatting libraries:
Day.js [added 2021-10-06] "Fast 2kB alternative to Moment.js with the same modern API"
Luxon [added 2017-03-29, thanks to Tampa] "A powerful, modern, and friendly wrapper for JavaScript dates and times." - MomentJS rebuilt from the ground up with immutable types, chaining and much more.
Moment.js [thanks to Mustafa] "A lightweight (4.3k) javascript date library for parsing, manipulating, and formatting dates" - Includes internationalization, calculations and relative date formats - Update 2017-03-29: Not quite so light-weight any more but still the most comprehensive solution, especially if you need timezone support. - Update 2021-02-28: No longer in active development.
date-fns [added 2017-03-29, thanks to Fractalf] Small, fast, works with standard JS date objects. Great alternative to Moment if you don't need timezone support.
SugarJS - A general helper library adding much needed features to JavaScripts built-in object types. Includes some excellent looking date/time capabilities.
strftime - Just what it says, nice and simple
dateutil - This is the one I used to use before MomentJS
node-formatdate
TimeTraveller - "Time Traveller provides a set of utility methods to deal with dates. From adding and subtracting, to formatting. Time Traveller only extends date objects that it creates, without polluting the global namespace."
Tempus [thanks to Dan D] - UPDATE: this can also be used with Node and deployed with npm, see the docs
There are also non-Node libraries:
Datejs [thanks to Peter Olson] - not packaged in npm or GitHub so not quite so easy to use with Node - not really recommended as not updated since 2007!
There's a library for conversion:
npm install dateformat
Then write your requirement:
var dateFormat = require('dateformat');
Then bind the value:
var day=dateFormat(new Date(), "yyyy-mm-dd h:MM:ss");
see dateformat
I have nothing against libraries in general. In this case a general purpose library seems overkill, unless other parts of the application process dates heavily.
Writing small utility functions such as this is also a useful exercise for both beginning and accomplished programmers alike and can be a learning experience for the novices amongst us.
function dateFormat (date, fstr, utc) {
utc = utc ? 'getUTC' : 'get';
return fstr.replace (/%[YmdHMS]/g, function (m) {
switch (m) {
case '%Y': return date[utc + 'FullYear'] (); // no leading zeros required
case '%m': m = 1 + date[utc + 'Month'] (); break;
case '%d': m = date[utc + 'Date'] (); break;
case '%H': m = date[utc + 'Hours'] (); break;
case '%M': m = date[utc + 'Minutes'] (); break;
case '%S': m = date[utc + 'Seconds'] (); break;
default: return m.slice (1); // unknown code, remove %
}
// add leading zero if required
return ('0' + m).slice (-2);
});
}
/* dateFormat (new Date (), "%Y-%m-%d %H:%M:%S", true) returns
"2012-05-18 05:37:21" */
Check the code below and the link to Date Object, Intl.DateTimeFormat
// var ts_hms = new Date(UTC);
// ts_hms.format("%Y-%m-%d %H:%M:%S")
// exact format
console.log(new Date().toISOString().replace('T', ' ').substring(0, 19))
// other formats
console.log(new Date().toUTCString())
console.log(new Date().toLocaleString('en-US'))
console.log(new Date().toString())
// log format
const parts = new Date().toString().split(' ')
console.log([parts[1], parts[2], parts[4]].join(' '))
// intl
console.log(new Intl.DateTimeFormat('en-US', {dateStyle: 'long', timeStyle: 'long'}).format(new Date()))
Easily readable and customisable way to get a timestamp in your desired format, without use of any library:
function timestamp(){
function pad(n) {return n<10 ? "0"+n : n}
d=new Date()
dash="-"
colon=":"
return d.getFullYear()+dash+
pad(d.getMonth()+1)+dash+
pad(d.getDate())+" "+
pad(d.getHours())+colon+
pad(d.getMinutes())+colon+
pad(d.getSeconds())
}
(If you require time in UTC format, then just change the function calls. For example "getMonth" becomes "getUTCMonth")
The javascript library sugar.js (http://sugarjs.com/) has functions to format dates
Example:
Date.create().format('{dd}/{MM}/{yyyy} {hh}:{mm}:{ss}.{fff}')
I am using dateformat at Nodejs and angularjs, so good
install
$ npm install dateformat
$ dateformat --help
demo
var dateFormat = require('dateformat');
var now = new Date();
// Basic usage
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM
// You can use one of several named masks
dateFormat(now, "isoDateTime");
// 2007-06-09T17:46:21
// ...Or add your own
dateFormat.masks.hammerTime = 'HH:MM! "Can\'t touch this!"';
dateFormat(now, "hammerTime");
// 17:46! Can't touch this!
// You can also provide the date as a string
dateFormat("Jun 9 2007", "fullDate");
// Saturday, June 9, 2007
...
Use the method provided in the Date object as follows:
var ts_hms = new Date();
console.log(
ts_hms.getFullYear() + '-' +
("0" + (ts_hms.getMonth() + 1)).slice(-2) + '-' +
("0" + (ts_hms.getDate())).slice(-2) + ' ' +
("0" + ts_hms.getHours()).slice(-2) + ':' +
("0" + ts_hms.getMinutes()).slice(-2) + ':' +
("0" + ts_hms.getSeconds()).slice(-2));
It looks really dirty, but it should work fine with JavaScript core methods
For date formatting the most easy way is using moment lib. https://momentjs.com/
const moment = require('moment')
const current = moment().utc().format('Y-M-D H:M:S')
Alternative #6233....
Add the UTC offset to the local time then convert it to the desired format with the toLocaleDateString() method of the Date object:
// Using the current date/time
let now_local = new Date();
let now_utc = new Date();
// Adding the UTC offset to create the UTC date/time
now_utc.setMinutes(now_utc.getMinutes() + now_utc.getTimezoneOffset())
// Specify the format you want
let date_format = {};
date_format.year = 'numeric';
date_format.month = 'numeric';
date_format.day = '2-digit';
date_format.hour = 'numeric';
date_format.minute = 'numeric';
date_format.second = 'numeric';
// Printing the date/time in UTC then local format
console.log('Date in UTC: ', now_utc.toLocaleDateString('us-EN', date_format));
console.log('Date in LOC: ', now_local.toLocaleDateString('us-EN', date_format));
I'm creating a date object defaulting to the local time. I'm adding the UTC off-set to it. I'm creating a date-formatting object. I'm displaying the UTC date/time in the desired format:
new Date(2015,1,3,15,30).toLocaleString()
//=> 2015-02-03 15:30:00
In reflect your time zone, you can use this
var datetime = new Date();
var dateString = new Date(
datetime.getTime() - datetime.getTimezoneOffset() * 60000
);
var curr_time = dateString.toISOString().replace("T", " ").substr(0, 19);
console.log(curr_time);
Here's a handy vanilla one-liner (adapted from this):
var timestamp =
new Date((dt = new Date()).getTime() - dt.getTimezoneOffset() * 60000)
.toISOString()
.replace(/(.*)T(.*)\..*/,'$1 $2')
console.log(timestamp)
Output: 2022-02-11 11:57:39
Use x-date module which is one of sub-modules of x-class library ;
require('x-date') ;
//---
new Date().format('yyyy-mm-dd HH:MM:ss')
//'2016-07-17 18:12:37'
new Date().format('ddd , yyyy-mm-dd HH:MM:ss')
// 'Sun , 2016-07-17 18:12:51'
new Date().format('dddd , yyyy-mm-dd HH:MM:ss')
//'Sunday , 2016-07-17 18:12:58'
new Date().format('dddd ddSS of mmm , yy')
// 'Sunday 17thth +0300f Jul , 16'
new Date().format('dddd ddS mmm , yy')
//'Sunday 17th Jul , 16'
I needed a simple formatting library without the bells and whistles of locale and language support. So I modified
http://www.mattkruse.com/javascript/date/date.js
and used it. See https://github.com/adgang/atom-time/blob/master/lib/dateformat.js
The documentation is pretty clear.
new Date().toString("yyyyMMddHHmmss").
replace(/T/, ' ').
replace(/\..+/, '')
with .toString(), This becomes in format
replace(/T/, ' '). //replace T to ' ' 2017-01-15T...
replace(/..+/, '') //for ...13:50:16.1271
example, see var date and hour:
var date="2017-01-15T13:50:16.1271".toString("yyyyMMddHHmmss").
replace(/T/, ' ').
replace(/\..+/, '');
var auxCopia=date.split(" ");
date=auxCopia[0];
var hour=auxCopia[1];
console.log(date);
console.log(hour);
Here's a lightweight library simple-date-format I've written, works both on node.js and in the browser
Install
Install with NPM
npm install #riversun/simple-date-format
or
Load directly(for browser),
<script src="https://cdn.jsdelivr.net/npm/#riversun/simple-date-format/lib/simple-date-format.js"></script>
Load Library
ES6
import SimpleDateFormat from "#riversun/simple-date-format";
CommonJS (node.js)
const SimpleDateFormat = require('#riversun/simple-date-format');
Usage1
const date = new Date('2018/07/17 12:08:56');
const sdf = new SimpleDateFormat();
console.log(sdf.formatWith("yyyy-MM-dd'T'HH:mm:ssXXX", date));//to be "2018-07-17T12:08:56+09:00"
Run on Pen
Usage2
const date = new Date('2018/07/17 12:08:56');
const sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
console.log(sdf.format(date));//to be "2018-07-17T12:08:56+09:00"
Patterns for formatting
https://github.com/riversun/simple-date-format#pattern-of-the-date
import dateFormat from 'dateformat';
var ano = new Date()
<footer>
<span>{props.data.footer_desc} <a href={props.data.footer_link}>{props.data.footer_text_link}</a> {" "}
({day = dateFormat(props.data.updatedAt, "yyyy")})
</span>
</footer>
rodape
Modern web browsers (and Node.js) expose internationalization and time zone support via the Intl object which offers a Intl.DateTimeFormat.prototype.formatToParts() method.
You can do below with no added library:
function format(dateObject){
let dtf = new Intl.DateTimeFormat("en-US", {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
});
var parts = dtf.formatToParts(dateObject);
var fmtArr = ["year","month","day","hour","minute","second"];
var str = "";
for (var i = 0; i < fmtArr.length; i++) {
if(i===1 || i===2){
str += "-";
}
if(i===3){
str += " ";
}
if(i>=4){
str += ":";
}
for (var ii = 0; ii < parts.length; ii++) {
let type = parts[ii]["type"]
let value = parts[ii]["value"]
if(fmtArr[i]===type){
str = str += value;
}
}
}
return str;
}
console.log(format(Date.now()));
You can use Light-Weight library Moment js
npm install moment
Call the library
var moments = require("moment");
Now convert into your required format
moment().format('MMMM Do YYYY, h:mm:ss a');
And for more format and details, you can follow the official docs Moment js
I think this actually answers your question.
It is so annoying working with date/time in javascript.
After a few gray hairs I figured out that is was actually pretty simple.
var date = new Date();
var year = date.getUTCFullYear();
var month = date.getUTCMonth();
var day = date.getUTCDate();
var hours = date.getUTCHours();
var min = date.getUTCMinutes();
var sec = date.getUTCSeconds();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = ((hours + 11) % 12 + 1);//for 12 hour format
var str = month + "/" + day + "/" + year + " " + hours + ":" + min + ":" + sec + " " + ampm;
var now_utc = Date.UTC(str);
Here is a fiddle
appHelper.validateDates = function (start, end) {
var returnval = false;
var fd = new Date(start);
var fdms = fd.getTime();
var ed = new Date(end);
var edms = ed.getTime();
var cd = new Date();
var cdms = cd.getTime();
if (fdms >= edms) {
returnval = false;
console.log("step 1");
}
else if (cdms >= edms) {
returnval = false;
console.log("step 2");
}
else {
returnval = true;
console.log("step 3");
}
console.log("vall", returnval)
return returnval;
}
it's possible to solve this problem easily with 'Date'.
function getDateAndTime(time: Date) {
const date = time.toLocaleDateString('pt-BR', {
timeZone: 'America/Sao_Paulo',
});
const hour = time.toLocaleTimeString('pt-BR', {
timeZone: 'America/Sao_Paulo',
});
return `${date} ${hour}`;
}
it's to show: // 10/31/22 11:13:25

creating date from a timestring in javascript

I am new to javascript and am trying to compare two date values ,I am getting two time value strings in the format
06:30:47 AM
01:10:47 PM
I need to compare these to find out if the first one is less than the other.I couldn't figure out how to do this in javascript.Can someone help?
o.h
I do not think that the standard implementation can parse this. I would do something like this:
function toDate(dateString) {
var timeComponents = dateString.replace(/\s.*$/, '').split(':');
if (dateString.indexOf("PM") > -1) {
timeComponents[0] += 12;
}
var date = new Date();
date.setHours(timeComponents[0]);
date.setMinutes(timeComponents[1]);
date.setSeconds(timeComponents[2]);
return date;
}
if (toDate('06:30:47 AM') > toDate('01:10:47 PM')) {
// ...
}
JavaScript's specified date/time parsing, what you can rely upon cross-browser, is surprisingly limited. For a long time, there was no single string date format that was mandated in the spec, and as of the recent 5th edition spec, the only mandated format is ISO-8601 (and some subsets). You can't yet rely on browsers having implemented that part of the 5th edition spec.
So you have a couple of choices:
Parse the string yourself and use the Date constructor that takes the individual parts of the date as numbers, e.g. new Date(year, month, day, hour, minute, second, ...). (You need only specify as many of those as you want, so for instance new Date(2010, 9, 14) is September 14th, 2010.)
Use a library like Moment that's already done the work for you. Moment lets you specify the format to parse.
Use the Date object. Check this: http://www.w3schools.com/jsref/jsref_obj_date.asp
Try putting the two values in Date variables and do this:
if(var1.valueOf() > var2.valueOf())
{
//Do Something
}
If your times are always in the format 00:00:00 AM then
var a="06:30:47 AM";
var b="01:10:47 PM";
var at=parseInt(a.substring(0,8).replace(/(^0+|:)/g,""));
var bt=parseInt(b.substring(0,8).replace(/(^0+|:)/g,""));
if (a.charAt(9)=="P") {at=at+120000};
if (b.charAt(9)=="P") {bt=bt+120000};
if (at<bt) {
// a is smaller
}
else
{
// a is not smaller
};
..should be cross-browser and time/format safe.
I tried something like this
var ts1="06:30:47 AM";
var ts2="01:10:47 PM";
var ds=new Date().toDateString();
var d1=new Date(ds+" "+ts1);
var d2=new Date(ds+" "+ts2);
if (!(d2>d1)){
alert("d1 should be less than d2");
}
Is there something wrong with this?
// specific formatter for the time format ##:##:## #M
var formatToMiliseconds = function(t){
t = t.split(/[:\s]/);
t = ((t[0] * 3600000) + (t[1] * 60000) * (t[2] * 1000)); // To ms
t = t + (/PM/i.test(t[3]) ? 43200000 : 0); // adjust for AM/PM
return t;
}
var time01 = formatToMiliseconds('06:30:47 AM');
var time02 = formatToMiliseconds('01:10:47 PM');
alert(time01 > time02); // false
allert(time01 < time02); // true
As a bonus, your time is now more compatible with the Date object and other time calculations.

Categories

Resources